Bird
Raised Fist0
Pythonprogramming~10 mins

Length and iteration methods in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Length and iteration methods
Start with a collection
Call len() function
Return number of items
Use for loop to iterate
Access each item one by one
End after last item
First, we find how many items are in a collection using len(). Then, we use a for loop to go through each item one by one until all are processed.
Execution Sample
Python
fruits = ['apple', 'banana', 'cherry']
print(len(fruits))
for fruit in fruits:
    print(fruit)
This code prints the number of fruits, then prints each fruit on its own line.
Execution Table
StepActionExpression EvaluatedResult/Output
1Create list 'fruits'fruits = ['apple', 'banana', 'cherry']fruits = ['apple', 'banana', 'cherry']
2Call len() on fruitslen(fruits)3
3Print lengthprint(3)3
4Start for loop, first itemfruit = fruits[0]'apple'
5Print first itemprint('apple')apple
6Next loop iterationfruit = fruits[1]'banana'
7Print second itemprint('banana')banana
8Next loop iterationfruit = fruits[2]'cherry'
9Print third itemprint('cherry')cherry
10Loop ends after last itemNo more itemsExit loop
💡 Loop ends because all items in the list have been processed.
Variable Tracker
VariableStartAfter Step 4After Step 6After Step 8Final
fruits['apple', 'banana', 'cherry']['apple', 'banana', 'cherry']['apple', 'banana', 'cherry']['apple', 'banana', 'cherry']['apple', 'banana', 'cherry']
fruitundefined'apple''banana''cherry''cherry'
Key Moments - 3 Insights
Why does the loop stop after printing 'cherry'?
The loop stops because it has gone through all items in the list. This is shown in execution_table row 10 where it says 'No more items' and the loop exits.
What does len(fruits) return and why?
len(fruits) returns 3 because there are three items in the list. This is shown in execution_table row 2 where len(fruits) evaluates to 3.
Why does the variable 'fruit' change each loop?
In each loop iteration, 'fruit' is assigned the next item from the list. This is shown in execution_table rows 4, 6, and 8 where 'fruit' takes values 'apple', 'banana', and 'cherry' respectively.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2. What value does len(fruits) return?
A3
B2
C0
DError
💡 Hint
Check the 'Result/Output' column at Step 2 in the execution_table.
At which step does the loop assign 'banana' to the variable 'fruit'?
AStep 4
BStep 6
CStep 8
DStep 10
💡 Hint
Look at the 'Expression Evaluated' column for the assignment of 'fruit' in the execution_table.
If the list had 4 items instead of 3, how would the execution_table change?
AThe loop would stop earlier.
BThe length printed would still be 3.
CThere would be one more loop iteration with a new fruit value.
DThe variable 'fruit' would not change.
💡 Hint
Refer to how the loop runs once per item in the list shown in the execution_table.
Concept Snapshot
len(collection) returns the number of items in a collection.
A for loop goes through each item one by one.
Inside the loop, a variable holds the current item.
Loop ends after the last item is processed.
Use print() to show values during iteration.
Full Transcript
This example shows how to find the length of a list using len() and then use a for loop to go through each item. First, the list 'fruits' is created with three items. Calling len(fruits) returns 3, which is printed. Then the for loop starts, assigning each fruit to the variable 'fruit' in turn. Each fruit is printed. The loop stops after the last fruit 'cherry' is printed because there are no more items. The variable 'fruit' changes each iteration to hold the current item. This process helps us count and access items in a collection easily.

Practice

(1/5)
1. What does the len() function do when used on a list in Python?
easy
A. It returns the number of items in the list.
B. It returns the last item in the list.
C. It adds all the items in the list.
D. It removes the first item from the list.

Solution

  1. Step 1: Understand the purpose of len()

    The len() function counts how many items are inside a collection like a list.
  2. Step 2: Apply to a list

    When used on a list, it returns the total number of elements present in that list.
  3. Final Answer:

    It returns the number of items in the list. -> Option A
  4. Quick 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
A. for fruit in fruits:
B. for fruits in fruit:
C. loop fruit in fruits:
D. foreach fruit in fruits:

Solution

  1. Step 1: Identify correct for-loop syntax in Python

    Python uses for variable in collection: to loop through items.
  2. Step 2: Match variable and collection names

    The variable should be singular (fruit) and collection plural (fruits) for clarity and correctness.
  3. Final Answer:

    for fruit in fruits: -> Option A
  4. Quick 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
A. 0
B. 3
C. ['a', 'b', 'c']
D. Error

Solution

  1. Step 1: Understand the loop iteration

    The loop goes through each item in the list items, which has 3 elements.
  2. Step 2: Track the count variable

    Each time the loop runs, count increases by 1. After 3 iterations, count becomes 3.
  3. Final Answer:

    3 -> Option B
  4. Quick 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
A. print() cannot be used inside a for loop.
B. Variable 'i' should be 'numbers'.
C. List 'numbers' should be a tuple.
D. Missing colon ':' after the for loop statement.

Solution

  1. 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.
  2. Step 2: Identify the missing colon

    The code line for i in numbers is missing the colon, causing a syntax error.
  3. Final Answer:

    Missing colon ':' after the for loop statement. -> Option D
  4. Quick 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
A. count = len(data)
B. count = sum(data)
C. count = sum(1 for x in data if x)
D. count = len([x for x in data if x == True])

Solution

  1. Step 1: Understand 'truthy' values in Python

    Truthy values are those that evaluate to True in conditions; 0, '', and None are falsy.
  2. 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.
  3. Final Answer:

    count = sum(1 for x in data if x) -> Option C
  4. Quick 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