0
0
Pythonprogramming~10 mins

len() function in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - len() function
Start with object
Call len() function
Check object type
Calculate number of items
Return length as integer
Use length in program
The len() function takes an object and returns the number of items it contains as an integer.
Execution Sample
Python
my_list = [10, 20, 30]
length = len(my_list)
print(length)
This code finds how many items are in the list and prints that number.
Execution Table
StepActionObjectlen() ResultOutput
1Define my_list[10, 20, 30]
2Call len(my_list)[10, 20, 30]3
3Assign length = 3
4Print length3
💡 Program ends after printing the length 3
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
my_listundefined[10, 20, 30][10, 20, 30][10, 20, 30][10, 20, 30]
lengthundefinedundefinedundefined33
Key Moments - 3 Insights
Why does len(my_list) return 3 and not the list itself?
len() counts how many items are inside the list, it does not return the list. See execution_table step 2 where len(my_list) gives 3.
Can len() be used on numbers like 123?
No, len() works on collections like lists, strings, or tuples. Numbers are not collections, so len(123) would cause an error.
What type of value does len() return?
len() always returns an integer representing the count of items, as shown in execution_table step 2 where the result is 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of length after step 3?
Aundefined
B[10, 20, 30]
C3
D0
💡 Hint
Check the 'len() Result' and 'Action' columns in step 3 of the execution_table.
At which step is the len() function called?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Action' column in the execution_table to find when len(my_list) is called.
If my_list had 5 items instead of 3, what would len(my_list) return at step 2?
A3
B5
C0
DError
💡 Hint
len() returns the number of items in the object, so it matches the list length.
Concept Snapshot
len(object)
- Returns the number of items in object
- Works on lists, strings, tuples, etc.
- Returns an integer
- Raises error if object has no length
- Use to find size of collections
Full Transcript
The len() function in Python counts how many items are inside a collection like a list or string. When you call len(my_list), Python checks the list and returns the number of items it contains as an integer. For example, if my_list has three items, len(my_list) returns 3. This value can be stored in a variable and printed. len() does not return the list itself, only the count of items. It works only on objects that have a length, like lists, strings, and tuples. Using len() on a number causes an error because numbers don't have length. The returned value is always an integer representing the size of the collection.