Home > Software design >  Why is list count not working as I expect with nested lists?
Why is list count not working as I expect with nested lists?

Time:02-08

I can count simple list but can not count list of lists.

list1 = ['R', 'E', 'R', 'E']
print(list1[0])
print(list1.count(list1[0]))

My logic thinks if above is true below should be true, but I was wrong.

list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
print(list1[0][1])
print(list1.count(list1[0][1]))

Output

R
2
R
0

CodePudding user response:

If you're trying to count the total # of occurrences in your list of lists- you can add in a loop like this:

list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
check = list1[0][1]  # R
count = 0
for list in list1:
    count  = list.count(check)
print(check)
print(count)

Output:

R
2

CodePudding user response:

A string is not equal to a list containing that string, so list1.count('R') won't find any matches in the second snippet.

You can use a list comprehension to extract the [1] element of each nested list, and then count the matches there.

print([x[1] for x in list1].count(list1[0][1]))
  •  Tags:  
  • Related