Home > Enterprise >  How to compare two lists which have strings in them in python?
How to compare two lists which have strings in them in python?

Time:07-25

I have these two strings:

list1 = ['M', 'AR0', 'I', 'K', 'Y']

list2 = ['M', 'AR0', 'IY', 'K', 'U']

I want the output "Yes" when the two elements in the same position are equal and "No" when the two elements in the same position are not equal, when comparing both of these strings. I want to do this using a for loop only because the strings that I will need to run my code on are longer than these. This is the code I have so far, but when I run it, it gives me this error "TypeError: list indices must be integers or slices, not str" So, how do I go through each element and check if they are equal to each other or not and then print what I want?

for i in list1:
    
  if list1[i] == list2[i]:
        
     print("Yes")
    
  else:
        
     print("No")

For example, in the two lists above, the elements in the second and fourth position are not equal.

CodePudding user response:

You can use zip:

for i, j in zip(list1, list2):
    if i == j:
        print('Yes')
    else:
        print('No')

Output:

Yes
Yes
No
Yes
No

CodePudding user response:

I would use zip() here along with a list comprehension:

list1 = ['M', 'AR0', 'I', 'K', 'Y']
list2 = ['M', 'AR0', 'IY', 'K', 'U']
z = ["Yes" if x[0] == x[1] else "No" for x in zip(list1, list2)]
print(z)  # ['Yes', 'Yes', 'No', 'Yes', 'No']

CodePudding user response:

You've 4 methods of doing so

your method

for i in range(len(list1)):
    if list1[i] == list2[i]:
        print('yes')
    else:
        print('no')

Using zip function

li = ['yes' if x == y else 'no' for x, y in zip(list1, list2)]

using map function

li = list(map(lambda x, y: 'yes' if x == y else 'no', list1, list2))

using list comprehension

li = ['yes' if list1[i] == list2[i] else 'no' for i in range(len(list1))]
  • Related