Reputation: 844
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}
Upvotes: 6
Views: 15747
Reputation: 3471
Assuming the lists as list1 and list2. list1 having 500 entries, having values from 0 to 1000, from the random generator code. list2 having x entries x is not 500. It can more than 500 or less than 500. Not clear from question, and having the values in range of 1 to 100.
// This will return the matching one.
set(list1).intersection(set(list2))
Upvotes: 0
Reputation: 226296
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]
Upvotes: 8
Reputation: 9935
If you dont want to use set
a = [1,2,3]
b = [3,2,4,5]
c = [i for i in a if i in b]
Upvotes: 3
Reputation: 336148
That's a job for sets:
>>> l1 = [1,2,3,4,5]
>>> l2 = [5,6,7,8,9]
>>> set(l1) & set(l2)
{5}
Upvotes: 6