Skip to content
Related Articles

Related Articles

Python – Count elements in tuple list

View Discussion
Improve Article
Save Article
  • Last Updated : 25 Aug, 2022
View Discussion
Improve Article
Save Article

Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using len() + generator expression This is the most basic method to achieve solution to this task. In this, we iterate over whole nested lists using generator expression and get the count using len(). 

Python3




# Python3 code to demonstrate working of
# Tuple list elements count
# using len() + generator expression
 
# initialize list
test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Tuple list elements count
# using len() + generator expression
temp = list((int(j) for i in test_list for j in i))
res = len(temp)
 
# printing result
print("The tuple list elements count : " + str(res))


Output : 

The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The tuple list elements count : 10

Method #2 : Using len() + map() + chain.from_iterable() The combination of the above methods can also be used to perform this task. In this, the extension of the finding count is done by a combination of map() and from_iterable(). 

Python3




# Python3 code to demonstrate working of
# Tuple list elements count
# using len() + map() + chain.from_iterable()
 
from itertools import chain
 
# initialize list
test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Tuple list elements count
# using len() + map() + chain.from_iterable()
res = len(list(map(int, chain.from_iterable(test_list))))
 
# printing result
print("The tuple list elements count : " + str(res))


Output : 

The original list : [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
The tuple list elements count : 10

Method #3: Using list comprehension 

Python3




test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
x=[j for i in test_list for j in i]
print(len(x))


Output

10

Method #4: Using enumerate function

Python3




test_list = [(2, 4), (6, 7), (5, 1), (6, 10), (8, 7)]
x = [j for i in enumerate(test_list) for j in i]
print(len(x))


Output

10

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!