Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare list in python to detect an equality

First, I am a novice at python programming and attempted much research within other questions but none that I could find that relate to something like this (all others were a bit more advanced) --- That said moving on.

The solution needed: Go through two two integer lists and compare for equality. Ideally I want it to continue going through the lists over and over till there is an equality (more on this after showing code). The number will be generated in list2 over and over till there is an equality.

Explanation to code: I have two lists that are generated via a random number generation. The lists are not equal in size. So list1 has 500 entries and list2 will have different amounts varying from 1 to 100.

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

Maybe I do not know much about looping, but I want it to loop through the list, I really do not know where to start from. Maybe I'm not using a loop like a for loop or while?

This is my number generators:

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

The second one would do some but would only have varying entries between 1 and 100. {I can take care of this myself}

like image 428
Bain Avatar asked Jan 27 '13 18:01

Bain


1 Answers

There are several possible interpretations of your question.

1) Loop over the lists pairwise, stopping when a pair is equal:

>>> 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) Loop over a list, stopping when any element is equal to any other element in the first list. This is a case where sets are useful (they do fast membership testing):

>>> 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) Loop over both like element-wise 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]
like image 136
Raymond Hettinger Avatar answered Nov 14 '22 23:11

Raymond Hettinger