Under the circumstances the lists would have to be the same length else we run the risk of raising an IndexError. Were we given two different length lists then we would have to use the length of the shorter list and so would not examine the latter values of the longer list.
Have you learned about zip()
, yet? That’s one way to get two lists the same length because it will discard surplus values on uneven lists.
>>> a = [2, 5, 8, 11, 14, 17]
>>> b = [3, 7, 11, 15, 19]
>>> c = [*zip(a, b)]
>>> c
[(2, 3), (5, 7), (8, 11), (11, 15), (14, 19)]
>>>
Notice how there is no 17
in the pairs since there was nothing to pair it up with.
For the purpose of this lesson, let’s continue with the assumption that the lists are the same length.
We can use the list of tuples to compare values by iterating and unpacking…
>>> print ([a for a, b in c if a == b])
[]
>>>
If you haven’t got to the unit on iterators yet, then ignore the above. For the heck of it, let’s use the technique to solve the lesson.
>>> def same_values(m, n):
return [a for a, b in zip(m, n) if a == b]
>>> print (same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))
[5, -10, 3]
>>>
For the time being, stick with what you know, and be sure to review it for what you might or might have learned from it.