How to compare two lists, object instances in python

Tell me if I have:

list1 = [1,6] list2 = [1] 

I want to do something if the values ​​in the list match!

Compare it and make stuff after that

+8
python
source share
3 answers

Mmm, like that?

 if list1 == list2: # compare lists for equality doStuff() # if lists are equal, do stuff after that 

Of course, you need to clarify what you mean by "if matching list values." The above will check to see if both lists have the same elements in the same position - that is, if they are equal.

EDIT:

The question is not clear, let some possible interpretations. To check if all the items in list1 in list2 , follow these steps:

 if all(x in list2 for x in list1): doStuff() 

Or do something with each item in list1 , which also belongs to list2 , do the following:

 for e in set(list1) & set(list2): doStuff(e) 
+17
source share

Use any() :

 >>> L1 = [1,6] >>> L2 = [1] >>> any(i in L1 for i in L2) True 

Basically, it goes through every element in L2 , and if any element in L2 is in L1 , then it will return True .

If you want to see if each item is in a different list and print which ones and which not:

 >>> for i in L2: ... if i in L1: ... print i, "is in L1" ... else: ... doStuff(i) 
+1
source share

A simple method, although not necessarily the most efficient (using all() instead of any() ):

 listsEqual = len(list1) == len(list2) and all(list1[i] == list2[i] for i in range(len(list1)) 
0
source share

All Articles