We use length and iteration methods to count items and go through each item in a list or other collection. This helps us work with groups of things easily.
Length and iteration methods in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
len(collection) for item in collection: # do something with item
len() gives the number of items in a collection like list, string, or tuple.
The for loop goes through each item one by one.
Examples
numbers, which is 4.Python
numbers = [1, 2, 3, 4] print(len(numbers))
Python
word = "hello" print(len(word))
Python
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
Python
for i in range(3): print(i)
Sample Program
This program counts how many items are in the list and prints each item one by one.
Python
items = ["pen", "book", "lamp"] print(f"There are {len(items)} items.") for item in items: print(f"Item: {item}")
Important Notes
You can use len() on many types like lists, strings, tuples, and dictionaries.
The for loop works with any collection that can be counted or listed.
Indentation is important in Python to show what is inside the loop.
Summary
len() tells you how many items are in a collection.
for loops let you do something with each item in a collection.
These tools help you handle groups of things easily and clearly.
Practice
1. What does the
len() function do when used on a list in Python?easy
Solution
Step 1: Understand the purpose of
Thelen()len()function counts how many items are inside a collection like a list.Step 2: Apply to a list
When used on a list, it returns the total number of elements present in that list.Final Answer:
It returns the number of items in the list. -> Option AQuick Check:
len(list) = number of items [OK]
Hint: Remember: len() counts items, it doesn't change them. [OK]
Common Mistakes:
- Thinking len() returns the last item
- Confusing len() with sum()
- Assuming len() removes items
2. Which of the following is the correct syntax to loop through all items in a list named
fruits?easy
Solution
Step 1: Identify correct for-loop syntax in Python
Python usesfor variable in collection:to loop through items.Step 2: Match variable and collection names
The variable should be singular (fruit) and collection plural (fruits) for clarity and correctness.Final Answer:
for fruit in fruits: -> Option AQuick Check:
for item in list: is correct syntax [OK]
Hint: Use 'for item in collection:' to loop in Python. [OK]
Common Mistakes:
- Swapping variable and collection names
- Using 'foreach' which is not Python syntax
- Writing 'loop' instead of 'for'
3. What will be the output of this code?
items = ['a', 'b', 'c']
count = 0
for item in items:
count += 1
print(count)medium
Solution
Step 1: Understand the loop iteration
The loop goes through each item in the listitems, which has 3 elements.Step 2: Track the count variable
Each time the loop runs,countincreases by 1. After 3 iterations, count becomes 3.Final Answer:
3 -> Option BQuick Check:
Loop runs 3 times, count = 3 [OK]
Hint: Count increments once per item; total equals list length. [OK]
Common Mistakes:
- Thinking count stays 0
- Confusing count with list itself
- Expecting a list output instead of a number
4. Find the error in this code snippet:
numbers = [1, 2, 3]
for i in numbers
print(i)medium
Solution
Step 1: Check for syntax errors in the for loop
Python requires a colon ':' at the end of the for loop line to start the block.Step 2: Identify the missing colon
The code linefor i in numbersis missing the colon, causing a syntax error.Final Answer:
Missing colon ':' after the for loop statement. -> Option DQuick Check:
for loop line must end with ':' [OK]
Hint: Always put ':' after for loop header line. [OK]
Common Mistakes:
- Forgetting the colon ':'
- Changing variable names unnecessarily
- Thinking print() can't be inside loops
5. Given a list
data = [3, 0, 5, '', None, 7], which code correctly counts only the items that are considered 'truthy' in Python?hard
Solution
Step 1: Understand 'truthy' values in Python
Truthy values are those that evaluate to True in conditions; 0, '', and None are falsy.Step 2: Analyze each option
count = len(data) counts all items, ignoring truthiness. count = sum(1 for x in data if x) sums 1 for each truthy item, correctly counting them. count = sum(data) sums values, not counts. count = len([x for x in data if x == True]) checks for exact True, missing other truthy values.Final Answer:
count = sum(1 for x in data if x) -> Option CQuick Check:
Sum 1 for truthy items counts them correctly [OK]
Hint: Use sum with condition to count truthy items. [OK]
Common Mistakes:
- Using len() counts all items, not just truthy
- Summing values instead of counting
- Checking equality to True instead of truthiness
