Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Compare two lists in a comprehension

I'm trying to understand how comprehensions work.

I would like to loop through two lists, and compare each to find differences. If one/or-more word(s) is different, I would like to print this word(s).

I'd like this all in one nice line of code, which is why I'm interested in comprehensions.

like image 559
Rhys Avatar asked Apr 14 '11 09:04

Rhys


People also ask

How do I compare the contents of two lists in Python?

Python sort() method and == operator to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How do you compare two lists containing strings in Python?

There are two ways of doing this: sorting the lists and using the == operator. converting them to set s and using the == operator.


1 Answers

Doing it in "one nice line of code" is code golf, and misguided. Make it readable instead.

for a, b in zip(list1, list2):
    if a != b:
       print(a, "is different from", b) 

This is not different in any significant way from this:

[print(a, "is different from", b) for a, b in zip(list1, list2) if a!=b]

Except that the expanded version easier to read and understand than the comprehension.

like image 65
Lennart Regebro Avatar answered Oct 20 '22 16:10

Lennart Regebro