Python (Scripting) - Count the elements in a list
by
Jeremy Canfield |
Updated: January 30 2024
| Python (Scripting) articles
Let's say you have the following list, which contains different types of elements, such as strings, booleans, and integers.
len can be used to count the number of elements in the list, regardless of the type of elements in the list, which would return 3 in this example.
#!/usr/bin/python
list = ["apple", 123, True]
print(len(list))
Often, this is used with some sort of if statement.
#!/usr/bin/python3
list = ["apple", 123, True]
if len(list) == 0:
print("there are 0 items in list")
elif len(list) == 1:
print("there is 1 item in list")
else:
print(f"there are {count} items in list")
Did you find this article helpful?
If so, consider buying me a coffee over at