The len() function can be used to count the number of elements in a Python list:
len(my_list)
3 Examples of Counting the Number of Elements in a List
Example 1: List that Contains Strings
To start with a simple example, create a list that contains 5 names:
names_list = ["Jeff", "Ben", "Maria", "Sophia", "Rob"]
print(names_list)
Run the script above, and you’ll get the following list:
['Jeff', 'Ben', 'Maria', 'Sophia', 'Rob']
You can then use the len() function in order to count the number of elements in the list:
names_list = ["Jeff", "Ben", "Maria", "Sophia", "Rob"]
number_of_elements = len(names_list)
print(number_of_elements)
Once you run the script in Python, you’ll get the following count:
5
Extend the list by additional 3 names, and then recount the number of elements:
names_list = ["Jeff", "Ben", "Maria", "Sophia", "Rob"]
names_list.extend(["Laura", "Elizabeth", "Justin"])
number_of_elements = len(names_list)
print(number_of_elements)
Here is the new count:
8
Example 2: List that Contains Numeric Data
Now create a list with numeric data:
numbers_list = [7, 22, 35, 28, 42, 15, 30, 11, 24, 17]
print(numbers_list)
Here is the list that you’ll get:
[7, 22, 35, 28, 42, 15, 30, 11, 24, 17]
Use the len() function to count the number of elements in the list:
numbers_list = [7, 22, 35, 28, 42, 15, 30, 11, 24, 17]
number_of_elements = len(numbers_list)
print(number_of_elements)
The result:
10
Example 3: List of Lists
What if you want to count the number of elements in a list of lists?
For instance, let’s create the following list of lists:
people_list = [
["Jon", "Smith", 21],
["Mark", "Brown", 38],
["Maria", "Lee", 42],
["Jill", "Jones", 28],
["Jack", "Ford", 55],
]
print(people_list)
You’ll now see this list of lists:
[['Jon', 'Smith', 21], ['Mark', 'Brown', 38], ['Maria', 'Lee', 42], ['Jill', 'Jones', 28], ['Jack', 'Ford', 55]]
Before you count all the elements, you’ll need to flatten the list of lists as follows:
people_list = [
["Jon", "Smith", 21],
["Mark", "Brown", 38],
["Maria", "Lee", 42],
["Jill", "Jones", 28],
["Jack", "Ford", 55],
]
flat_people_list = [i for x in people_list for i in x]
print(flat_people_list)
Here is how the flatten list would look like:
['Jon', 'Smith', 21, 'Mark', 'Brown', 38, 'Maria', 'Lee', 42, 'Jill', 'Jones', 28, 'Jack', 'Ford', 55]
Finally, you can use the script below to get the total count:
people_list = [
["Jon", "Smith", 21],
["Mark", "Brown", 38],
["Maria", "Lee", 42],
["Jill", "Jones", 28],
["Jack", "Ford", 55],
]
flat_people_list = [i for x in people_list for i in x]
number_of_elements = len(flat_people_list)
print(number_of_elements)
The result:
15