0
0
Pythonprogramming~10 mins

List length and membership test in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - List length and membership test
Start with a list
Check length with len()
Use 'in' to test membership
Return length and membership result
We start with a list, then find its length using len(), and check if an item is in the list using 'in'. Finally, we get the results.
Execution Sample
Python
my_list = [2, 4, 6, 8]
length = len(my_list)
has_six = 6 in my_list
print(length, has_six)
This code finds the length of the list and checks if 6 is inside it, then prints both results.
Execution Table
StepActionExpression EvaluatedResultOutput
1Create listmy_list = [2, 4, 6, 8][2, 4, 6, 8]
2Calculate lengthlen(my_list)4
3Check membership6 in my_listTrue
4Print resultsprint(length, has_six)4 True
💡 All steps completed, program ends after printing.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
my_listundefined[2, 4, 6, 8][2, 4, 6, 8][2, 4, 6, 8][2, 4, 6, 8]
lengthundefinedundefined444
has_sixundefinedundefinedundefinedTrueTrue
Key Moments - 2 Insights
Why does len(my_list) return 4 instead of the last number in the list?
len(my_list) counts how many items are in the list, not the value of any item. See step 2 in execution_table where len(my_list) is 4 because there are 4 items.
Why does '6 in my_list' return True even though 6 is not the first item?
'in' checks every item in the list until it finds 6. It doesn't matter where 6 is. Step 3 shows '6 in my_list' is True because 6 is present.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the value of length?
A8
B4
C6
DUndefined
💡 Hint
Check the 'Result' column at step 2 in execution_table.
At which step does the program check if 6 is in the list?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for membership test.
If we check '5 in my_list' instead of '6 in my_list', what would be the result at step 3?
AError
BTrue
CFalse
DUndefined
💡 Hint
Since 5 is not in the list, membership test returns False.
Concept Snapshot
List length and membership test in Python:
- Use len(list) to get number of items.
- Use 'item in list' to check if item exists.
- len() returns an integer count.
- 'in' returns True or False.
- Both are simple and fast ways to inspect lists.
Full Transcript
This example shows how to find the length of a list and check if a value is inside it. First, we create a list with four numbers. Then, we use len() to count how many items are in the list, which is 4. Next, we check if the number 6 is in the list using '6 in my_list', which returns True because 6 is present. Finally, we print both results: 4 and True. This helps us understand how to quickly get list size and test membership in Python.