A user selects the first task in a list that might be empty.
What You Need to Understand
A list index is valid only within the range from -len(items) to len(items)-1. Accessing an invalid index raises IndexError; checking a list first can prevent many avoidable failures.
When to Use It
A user selects the first task in a list that might be empty.
Step-by-Step Python Example
tasks = []
if tasks:
print(tasks[0])
else:
print("No tasks available")
print(len(tasks))
How the Example Works
The condition checks whether any task exists before indexing. An empty list prints a helpful message instead of raising an error.
Example Output
No tasks available
0
None
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
values = [10, 20]
index = 2
print(values[index] if 0 <= index < len(values) else None)
Important Behavior and Edge Cases
Negative indexes also have limits: items[-1] fails on an empty list. Slicing out of range is generally safe and returns a shorter result.
Try It Yourself
Write a safe last-item lookup for a list that may be empty.
Common Beginner Mistakes
- Negative indexes also have limits:
items[-1]fails on an empty list. Slicing out of range is generally safe and returns a shorter result. - Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- A list index is valid only within the range from
-len(items)tolen(items)-1. - The condition checks whether any task exists before indexing.
- Negative indexes also have limits:
items[-1]fails on an empty list.