List Methods continued...
In Part 1, we learned about common list methods like .pop(), .clear(), .append(), and .insert(). In this section, we will explore other essential methods used to manage data in Python.
The .index() Method: The "Spot Finder"
Sometimes you don't want to add or remove someone; you just want to know where they are standing.
The .index() method acts like a searchlight. You give it a name, and it tells you the exact position (index number) of that person in the line.
How it works:
- Print position.
Using Search Ranges (Start and Stop)
Python also allows you to narrow down the search. This is useful if the line is very long and you only want to look at a specific section.
Syntax: list.index(value, start, stop)
- Start: Where to begin looking.
- Stop: Where to stop looking (Python stops searching just before this index).
The "Found" Example:
If we look for 'Bob' between index 0 and index 5:
- Try to find 'Fionn' between 0 and 3.
Key Rules for .index():
- First Match Only: If there are two "Alice's," .index() will only return the position of the first Alice it finds.
- Case Sensitive: Searching for 'alice' (lowercase) will result in an error if the list has 'Alice' (uppercase).
- The Crash: If the item isn't in the range you specified (or isn't in the list at all), the program will stop running with an error.
Defensive Programming
Using the in Keyword: The "Safety Check"
As we saw with .index(), asking Python to find someone who isn't there causes the whole program to crash with an error. In the real world, we want our code to be "robust"—meaning it can handle unexpected situations without breaking.
To avoid errors, we can use the Python keyword in. This keyword acts like a quick "Yes/No" question to check if an item exists in the list before we try to do anything with it.
How it works:
The in keyword returns a Boolean value: either True or False.
- Is Zelda in the line?
Why this matters: Good code anticipates missing data.
- Professionalism:
- User Experience: It’s much better to tell a user "Item not found" than to have the entire application close with a ValueError.
- Simplicity: The in keyword is readable and looks almost like plain English.
The .count() Method: The "Tally Counter"
Finally, let’s look at the .count() method. While .index() tells you where someone is, .count() tells you how many times a specific value appears in your list.
In our movie theater analogy, imagine a very large family all has the same name, or perhaps one person accidentally joined the line twice!
How it works:
You provide the value you are looking for, and Python returns an integer representing the total number of matches.
- Create a new variable alice_count.
- Print the number of Alices
Important Details for .count():
- No Match? No Problem: Unlike .index(), which crashes if it doesn't find a value, .count() is much friendlier. If the item isn't in the list, it simply returns 0.
- Case Sensitivity: Just like other methods, .count('alice') is different from .count('Alice').
- Exact Matches: It only counts items that are an exact match for what you put in the parentheses.
Summary Table: Finding Items
| Method / Keyword | Purpose | Result if Not Found |
|---|---|---|
| in | Checks if an item exists. | Returns False |
| .index() | Finds the location of an item. | Crashes (ValueError) |
| .count() | Counts how many of an item exist. | Returns 0 |
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named list_methods.py in your part23 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Finding the Spot
Someone is calling out for 'Charlie' to let him know his snacks are ready. You need to find exactly where he is standing.
-
Starting List:
line = ['Alice', 'Bob', 'Charlie', 'Kieran', 'Fionn'] -
Task: Use
.index()to find the position of 'Charlie' and store it in a variable calledposition. -
Goal: Print the
positionvariable. (It should be 2).
Exercise 2: Searching the Range
You want to see if 'Bob' is standing in the first half of the line (between index 2 and 5).
-
Starting List:
line = ['Alice', 'Bob', 'Charlie', 'Kieran', 'Fionn'] -
Task: Try to use
line.index('Bob', 2, 5). - Goal: Observe the error in your terminal. Write a comment in your code explaining why it crashed even though 'Bob' is in the list.
Exercise 3: The Safety Check
To prevent your code from crashing, you should always check if someone is in line before looking for their index.
-
Starting List:
line = ['Alice', 'Bob', 'Charlie'] -
Task: Use the
inkeyword to check if 'Zelda' is in the list. -
Goal: Print the result of the check. It should
return
False.
Exercise 4: Tallying Names
A few people in the line have the same name. You need to count them.
-
Starting List:
line = ['Alice', 'Bob', 'Alice', 'Charlie', 'Alice'] -
Task: Use
.count()to find out how many times 'Alice' appears. - Goal: Print the result. It should be 3.
Exercise 5: The "Safe" Search
Combine your skills! Create a script that searches for a name only if it exists.
-
Starting List:
line = ['Alice', 'Bob', 'Charlie'] -
Task: Create a variable
search_name = 'Kieran'. Use anifstatement withinto check if he is there. If he is, print his index. If not, print "Not found". - Goal: Run the code and ensure it prints "Not found" without crashing.
Don't Forget to commit and Push!