Not the most efficient one, but by far the most obvious way to do it is:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}
if order is significant you can do it with list comprehensions like this:
>>> [i for i, j in zip(a, b) if i == j]
[5]
(only works for equal-sized lists, which order-significance implies).
Answer from SilentGhost on Stack OverflowNot the most efficient one, but by far the most obvious way to do it is:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}
if order is significant you can do it with list comprehensions like this:
>>> [i for i, j in zip(a, b) if i == j]
[5]
(only works for equal-sized lists, which order-significance implies).
Use set.intersection(), it's fast and readable.
>>> set(a).intersection(b)
set([5])
how to best compare two lists using a for loop?
How does Python compare 2 lists?
Compare two lists
Finding difference between two lists without removing duplicates
The task is to take two lists and print the index of every value that matches using a for loop.
a = [0,1,2,3,4,6,4,5,8]
b = [0,5,6,7,4,6,3,5,8]
newlist = []
for number in a:
if number == b[number]:
newlist.append(b.index(number))
print(newlist)The output should be: 0,4,5,8
The output is: 0,4,4,8
After some research I found a lot of better ways of doing this exercise (list comprehensions etc.) . I can not figure out though what the mistake is in this example. I already tried variations of this using range() - for number in range(len a)
What am I missing here?
Edit: sry - I meant the output should be 0,4,5,7,8