Compare list in python for equality

Firstly, I am new to python programming and have tried a lot of research on other issues, but not one of them that I could find related to something like this (everyone else was a bit more advanced).

Necessary Solution: Go through two two integer lists and compare them for equality. Ideally, I want him to continue browsing the lists again and again until there is equality (more on this after showing the code). The number will be generated in list2 again and again until equality is established.

Explanation for the code . I have two lists that are generated using random number generation. Lists are not equal in size. Thus, list1 has 500 entries, and list2 will have different numbers from 1 to 100.

 #current attempt to figure out the comparison. if (list1 = list2): print(equalNumber) 

Maybe I don't know much about loops, but I want him to iterate over the list, I really don't know where to start. Maybe I don't use a loop like a for or while loop?

These are my number generators:

  for i in range(0,500): randoms = random.randint(0,1000) fiveHundredLoop.append(randoms) 

The second one will do some, but will have variable records between 1 and 100. {I will take care of myself}

+6
source share
4 answers

There are several possible interpretations of your question.

1) Go through the lists in pairs, stopping when the pair is equal to:

 >>> s = [10, 14, 18, 20, 25] >>> t = [55, 42, 18, 12, 4] >>> for x, y in zip(s, t): if x == y: print 'Equal element found:', x break Equal element found: 18 

2) Navigate through the list, stopping when any item is equal to any other item in the first list. This is the case when kits are useful (they quickly test membership):

 >>> s = {18, 20, 25, 14, 10} >>> for x in t: if x in s: print 'Equal element found', x break Equal element found 18 

3) Iterate over the same elements, and compare their values:

 >>> s = [10, 14, 18, 20, 25] >>> t = [55, 42, 18, 12, 4] >>> [x==y for x, y in zip(s, t)] [False, False, True, False, False] 
+8
source

This quest is for sets:

 >>> l1 = [1,2,3,4,5] >>> l2 = [5,6,7,8,9] >>> set(l1) & set(l2) {5} 
+6
source

If you do not want to use set

 a = [1,2,3] b = [3,2,4,5] c = [i for i in a if i in b] 
+3
source

Assuming lists like list1 and list2. list1 contains 500 entries with values ​​from 0 to 1000 from the random generator code. list2 with x-elements x is not 500. It can be more than 500 or less than 500. It is not clear from the question and has values ​​in the range from 1 to 100.

 // This will return the matching one. set(list1).intersection(set(list2)) 
0
source

All Articles