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 that indicates whether each element of x and y is identical to get:

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

How to do this using list comprehension?

My attempt:

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

But I do not know how to do this.

+8
python list list-comprehension
source share
3 answers

Are you looking for zip

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

But it is better to add int to get the desired result.

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

else you will get a list, for example [True, False, True, False, False]


As ajcr is mentioned in comment , it is better to use itertools.izip instead of zip if the lists are very long. This is because an iterator is created 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] 
+22
source share

You can change it a bit and do:

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

If you are using Python3 - change xrange to range

+3
source share

While the question indicated understanding the list, and the answers above are probably better, I thought I would have something in common with a recursive solution:

 def compare_lists(a, b, res=[]): if len(a) == len(b): if a == []: return res else: if a[0] == b[0]: res.append(1) else: res.append(0) return compare_lists(a[1:], b[1:]) else: return "Lists are of different length." 
+1
source share

All Articles