0

I am trying to compare y with x, such that it will return the amount of matches and it strictly follows the value of y.

For example, in this scenario, it should return a count of 2 as there are 2 matches of ['a', 'b'].

x = ['a', 'b'], ['b', 'c'], ['d', 'c'], ['a', 'b']
y = ['a', 'b']
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
nalyr
  • 141
  • 7

2 Answers2

2

Use the list 'count' method.

x = [['a', 'b'], ['b', 'c'], ['d', 'c'], ['a', 'b']]
y = ['a', 'b']

my_count = x.count(y) # 2
Etch
  • 462
  • 3
  • 12
  • Hi, will there be a difference if I create an overall list for these lists compared to if I separate them by their individual lists? Thank you! – nalyr Sep 30 '21 at 13:43
  • When you don't wrap them, it automatically wraps them in a tuple. So not wrapping them like you did is the same as ```x = (['a', 'b'], ['b', 'c'], ['d', 'c'], ['a', 'b'])```. But it wouldn't differ in this case. – Etch Sep 30 '21 at 14:04
  • Tuples are similar to lists but the key difference is that tuples are immutable, which means it cannot be changed *(e.g. cannot append elements to a tuple)* – Etch Sep 30 '21 at 14:07
0

If I understand what you want, the result will be 2, so you have to iterate through the x list and for each value compare it with y, right?

x = [['a', 'b'], ['b', 'c'], ['d', 'c'], ['a', 'b']]
y = ['a', 'b']
sum = 0
for i in x:
  if i == y:
    sum+=1
print(sum)
  • Hi, I tried this method and I dont think it will probably work. If I am not wrong, such lists are unable to read as an index, or I am not sure is there another way round to make it work such that it is able to read it as an index. Thank you! – nalyr Sep 30 '21 at 13:37