Reputation: 2738
I have a list that contains the name, age, and id of a person respectively. I want to count the number of occurrences of a given id within the list.
When I try:
alist=[(('john', 37), 8),(('john', 37), 8)]
count_ID=alist.count(8)
print count_ID
I receive:
count_ID returns 0
I expect it to return 2 in this example, as the list has 2 items that have id=8. How can I fix this?
Upvotes: 1
Views: 268
Reputation: 236014
Try this instead:
alist = [ (('john', 37), 8), (('john', 37), 8) ]
sum(1 for x in alist if x[1] == 8)
You have to specify somehow that the id
field is present as the second element in the tuple, then filter out only those tuples with id == 8
and finally sum 1 for each one that was found - alternatively we could find out the length of the resulting list, but why creating a temporary list when a generator suffices?
As pointed out in the comments, this also works:
sum(x[1] == 8 for x in alist)
The above snippet works because in the comparison x[1] == 8
a True
value evaluates to 1
and a False
evaluates to 0
.
Upvotes: 2
Reputation: 298206
alist.count(8)
would only work if 8
was an element of alist
:
>>> alist = [(('john', 37), 8),(('john', 37), 8)]
>>> 8 in alist
False
8
, however, is an element of the first element of your list:
>>> 8 in alist[0]
True
So to count the number of occurrences, you have to check to see if 8
is in each of the elements of alist
:
>>> sum(i[1] == 8 for i in alist)
2
Upvotes: 2