Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing values in two lists in Python

In Python 2.7, I have two lists of integers:

x = [1, 3, 2, 0, 2]
y = [1, 2, 2, 3, 1]

I want to create a third list which indicates whether each element in x and y is identical, to yield:

z = [1, 0, 1, 0, 0]

How can I do this using list comprehension?

My attempt is:

z = [i == j for i,j in ...]

But I don't know how to complete it.

like image 622
Karnivaurus Avatar asked Oct 07 '15 15:10

Karnivaurus


People also ask

How do you compare two lists containing strings in Python?

Comparing if two lists are equal in python The easiest way to compare two lists for equality is to use the == operator. This comparison method works well for simple cases, but as we'll see later, it doesn't work with advanced comparisons. An example of a simple case would be a list of int or str objects.

Can you compare a set to a list Python?

Comparing lists in Python Two of the most popular methods are set() and cmp() . The set() function creates an object that is a set object. The cmp() function is used to compare two elements or lists and return a value based on the arguments passed.


2 Answers

You are looking for zip

z = [i == j for i,j in zip(x,y)]

But you better add int call to get your desired output

>>> z = [int(i == j) for i,j in zip(x,y)]
>>> z
[1, 0, 1, 0, 0]

else you'll get a list like [True, False, True, False, False]


As ajcr mentions in a comment, it is better to use itertools.izip instead of zip if the lists are very long. This is because it returns an iterator instead of a list. This is mentioned in the documentation

Like zip() except that it returns an iterator instead of a list.

demo

>>> from itertools import izip
>>> z = [int(i == j) for i,j in izip(x,y)]
>>> z
[1, 0, 1, 0, 0]
like image 81
Bhargav Rao Avatar answered Sep 20 '22 03:09

Bhargav Rao


You can change it a little bit and do:

[x[i] == y[i] for i in xrange(len(x))]

If you use Python3 - change xrange to range

like image 25
SomethingSomething Avatar answered Sep 20 '22 03:09

SomethingSomething