0
0
Pythonprogramming~5 mins

List length and membership test in Python

Choose your learning style9 modes available
Introduction

We use list length to know how many items are in a list. Membership test helps us check if an item is inside the list.

Counting how many friends you have in a list.
Checking if a grocery item is already in your shopping list.
Finding out if a word exists in a list of vocabulary words.
Making sure a number is part of a list before using it.
Verifying if a task is in your to-do list before marking it done.
Syntax
Python
my_list = [item1, item2, item3]
length = len(my_list)
if element in my_list:
    # do something

len() is a built-in function that returns the number of items in the list.

The in keyword checks if an element exists in the list and returns True or False.

Examples
Empty list has length 0 and no elements inside.
Python
my_list = []
print(len(my_list))  # Output: 0
print(5 in my_list)  # Output: False
List with one element has length 1 and membership test returns True for that element.
Python
my_list = [10]
print(len(my_list))  # Output: 1
print(10 in my_list)  # Output: True
List with multiple elements. Membership test works for first, last, and missing elements.
Python
my_list = [1, 2, 3, 4, 5]
print(len(my_list))  # Output: 5
print(1 in my_list)  # Output: True
print(5 in my_list)  # Output: True
print(6 in my_list)  # Output: False
Sample Program

This program creates a shopping list, prints its length, and checks if certain items are in the list.

Python
def main():
    shopping_list = ['milk', 'eggs', 'bread']
    print(f"Shopping list has {len(shopping_list)} items.")

    item_to_check = 'eggs'
    if item_to_check in shopping_list:
        print(f"{item_to_check} is in the shopping list.")
    else:
        print(f"{item_to_check} is NOT in the shopping list.")

    item_to_check = 'butter'
    if item_to_check in shopping_list:
        print(f"{item_to_check} is in the shopping list.")
    else:
        print(f"{item_to_check} is NOT in the shopping list.")

if __name__ == '__main__':
    main()
OutputSuccess
Important Notes

Time complexity for len() is O(1) because Python stores the list size.

Membership test in takes O(n) time because it checks each item until it finds a match or reaches the end.

Common mistake: Using == instead of in to check membership.

Use len() when you need the count of items. Use membership test to check presence before actions like removal or update.

Summary

len() tells how many items are in a list.

in checks if an item is inside the list and returns True or False.

These tools help you work with lists safely and correctly.