In this tutorial, I will show you different ways of how to count elements of list in python. so without wasting any time let’s get started.
1. By Using Builtin len() Function
len() is the builtin function which on calling returns the number of elements inside the object.
# program to count elements of list in python data = [1,2,5,"a","banana"] print("Size Of Data :",len(data))
Here is the output of above code.
2. By using for-loop
In this code example, we have used for loop to count elements of the list.
Here is the algorithm.
- We first initialize a count variable to 0.
- We then iterate through the input list.
- We then increment the count variable by 1.
- Finally, we return the count to the caller.
# function to count elements of list in python def find_size(data): count = 0 # initialize the variable to 0 for i in data: # iterate through data count += 1 # increment count by 1 return count data = [8,5,3,6,7,1] s = find_size(data) print(s)
3. Count Occurrences of a Given Element
In the below code, we have used the count method of the list to count the occurrence of an element.
>>> data = [1,2,1,3,5,1] >>> data.count(1) # count how many times 1 appears in data 3
That’s the wrap for this tutorial.
Also read about how to remove duplicates from list