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.
List length and membership test in 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.
my_list = [] print(len(my_list)) # Output: 0 print(5 in my_list) # Output: False
my_list = [10] print(len(my_list)) # Output: 1 print(10 in my_list) # Output: True
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
This program creates a shopping list, prints its length, and checks if certain items are in the list.
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()
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.
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.