Python counts the number of items in the list
A simple example code gets the number of elements in a list.
Built-in Function len()
# List of just integers list_a = [1, 2, 3, 0] print(len(list_a)) # List of integers, floats, strings, booleans list_b = [4, 1.2, "hello world", True] print(len(list_b))
Using a for Loop
Declare a counter variable to count the number of elements in the list using a for loop and print the counter after the loop in Python gets terminated.
item_list = [1, 2, 3, 4] # declare a counter variable count = 0 # iterate on items using for-loop # and keep increasing the value of count for i in item_list: # increment the value of count count = count+1 print("No of elements in the list are:", count)
Output: No of elements in the list are: 4
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.