The len() function can be used to count the number of elements in a Python list:
len(my_list)
In this short guide, you’ll see 3 examples of counting the number of elements in:
- List that contains strings
- List that includes numeric data
- List of lists
(1) Count the Number of Elements in a Python List that Contains Strings
To start with a simple example, let’s create a list that contains 5 names:
names_list = ['Jeff', 'Ben', 'Maria', 'Sophia', 'Rob'] print(names_list)
Run the syntax 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'] print(len(names_list))
Once you run the code in Python, you’ll get the count of 5.
Let’s 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']) print(len(names_list))
You’ll now get the count of 8.
(2) Count the Number of Elements in a Python List that Includes Numeric Data
Let’s 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]
To count the number of elements in the list, use the len() function:
numbers_list = [7,22,35,28,42,15,30,11,24,17] print(len(numbers_list))
You’ll get the count of 10.
(3) Count the Number of Elements in a 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 code 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] print(len(flat_people_list))
Once you run the code, you’ll get the count of 15.