1

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?

Cœur
  • 34,719
  • 24
  • 185
  • 251
John Smith
  • 2,496
  • 7
  • 27
  • 34

3 Answers3

2

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.

Óscar López
  • 225,348
  • 35
  • 301
  • 374
2

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
Blender
  • 275,078
  • 51
  • 420
  • 480
2

The list has to be flattern. Python does not count nested list. So it'd be:

alist=[(('john', 37), 8),(('john', 37), 8),8,8]

for python to return 2

and here is the ways to flattern the list

Community
  • 1
  • 1
Relaed
  • 46
  • 5