thecodezone.
The Code Zone
Short steps, at your pace · Free lessons and practice · Member video walkthroughs
Save your next small win.

Checking your account…

03.01 · Find and sort items / Watch · 12 min

Find the first matching item safely

Index zero is a real match. A missing item raises an error instead of returning a position.

Activity 1 of 4 in Find and sort items

All courses

Python 3: Lists / 03.01

Find items by value

Not started

Use membership, index and a specific exception handler to handle missing values.

More options

Your lesson progress

Walkthrough: not startedPractice: not started

Empty: not started. Yellow: in progress. Green: complete. Marking the whole activity complete does not replace your test results. These circles save in this browser for this pilot.

Rob finds the first red card at index 0, then safely reports a missing purple card.
Rob’s comic strip · Find and sort items

ORIGINAL WALKTHROUGH · 5:05

Watch with Rob.

Pause whenever you want to try a change. You can return to the lesson at any time.

LEARN WITH THE CODE ZONE

Unlock this video walkthrough

Written lessons and coding practice are free. Video walkthroughs are included with a paid Code Zone membership or an active free trial.

Have a Code Zone website account? Use your learning account’s email to get a six-digit sign-in code, or use your existing website password.

Need a website account? Paid Skool members and active trial members can use the email from their membership questions to request a sign-in code. No invite link or Skool password needed.

Close this window to keep practicing. After signing in, you’ll return to this lesson.

Video walkthroughs are included with an active Code Zone membership. The written lesson and practice are free.

Open video & code editor (opens in a new tab)

Starter source code for VS Code

Copy the source below or download the file to follow along in VS Code.

The download includes a lesson link in each file and a README so you can find your way back.

main.py
main.pypython · example
# Code along with Rob: Find items by value
# Find the first matching position, including index zero.
# Compare a membership guard with catching ValueError.
# Try an existing item and a missing item.
# Predict each result, then press play.

index returns a position, not the item

colors.index("red") returns the zero-based position of the first equal value. A duplicate later in the list does not change that first result. Position 0 is a valid answer; do not use if position to decide whether an item was found.

Unlike some other languages, Python list.index does not return -1 for a missing item. It raises ValueError.

index returns a position, not the item
lists.pypython · example
colors = ["red", "blue", "red", "green"]
position = colors.index("red")
print(position)  # 0
print(colors[position])  # red
Open workspace to paste this example (opens in a new tab)

Check membership before asking for an index

Use value in colors to ask whether a matching item exists. Call index only in the branch where that membership test is true. The else branch explains that no matching item exists.

The list is unchanged throughout this search. Membership answers True or False; index answers a number.

Check membership before asking for an index
lists.pypython · example
colors = ["red", "blue", "green"]
wanted = "purple"
if wanted in colors:
    print(colors.index(wanted))
else:
    print("Color not found")
Open workspace to paste this example (opens in a new tab)

Catch the specific missing-value error

try runs its indented statements. If colors.index raises ValueError, Python runs the matching except block instead. Code after the block can continue.

Catch ValueError for this known situation rather than hiding every error with a bare except. A membership check and a specific exception handler are two options; neither is universally better in all programs.

Catch the specific missing-value error
lists.pypython · example
colors = ["red", "blue", "green"]
try:
    position = colors.index("teal")
    print(position)
except ValueError:
    print("teal not found")
print("Search complete")
Open workspace to paste this example (opens in a new tab)

Build it one step at a time

Prefer learning by typing? Work through short instructions, run the Python code and check each change before continuing. Your guided project saves separately from the challenge below.

The mini-lesson opens in a new tab. Your own code carries forward; each step has a focused check and an optional hint.

Start mini-lesson(opens in a new tab)

4 steps · Saved work · Instant feedback

YOUR TURN

Handle each search outcome

Find Pixel; guard purple with membership; handle missing teal with except ValueError. Preserve both input lists and print the three requested results.

Expected output
3
4
teal not found

Keep the starting inputs. Print these lines in this order, without extra output.

  • Keep the requested movie position
  • Keep the requested purple position
  • Keep the requested purple message
  • Keep the requested teal message
  • Keep the requested movies
  • Keep the requested colors
  • Output 1 matches the requested result
  • Output 2 matches the requested result
  • Output 3 matches the requested result

Edit Python, then run it. Check challenge checks your output and the listed Python requirements. Your code saves on this browser after a short pause. Sign in and choose Save account draft to keep it across devices. Word wrap is enabled.

Ready to checkRun the checks to see your results here.

Need a nudge?

Search the list by value

movies.index("Pixel") returns a number. Keep the actual movie list and search value rather than hardcoding that number.

Give missing colors a deliberate path

Check "purple" in colors before index. Catch ValueError around the teal index call. Convert a found numeric position with str when storing the message.

Replace your editor code?

Your current work will be replaced. Choose Cancel to keep it.

Ready to try it?

Practice in your browser and see your results.

Progress details

Have a question?

Ask the Code Zone community.

Ask a question in The Code Zone (opens in a new tab)

Continue learning

ONE STEP FORWARD

Use membership or a ValueError handler for missing items. Treat index 0 as a successful match.