0

Is there a way to iterate over two lists of different length at the same time without combining them?

I tried itertools.product(list1, list2) but that's very similar to a nested loop. So the second list gets iterated for each item of the first list, which is not what I want.

I want to compare both lists and see if they match.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
random-xyz
  • 137
  • 4
  • 14
  • 1
    How about [`zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest)? – ggorlen Nov 16 '19 at 16:17
  • Thank you so much, that seems to have done the trick! – random-xyz Nov 16 '19 at 16:45
  • Does this answer your question? [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – mkrieger1 Feb 11 '20 at 15:57

1 Answers1

1

If your purpose is to check for differences, you can use sets. Let's say you have two lists, like

a=["one", "two", "three"]
b=["one", "other"]

You can check the difference by converting them to set:

print(set(a) - set(b))

The order matters: the first item is the one you are checking against the second:

print(set(a) - set(b)) returns {'three', 'two'} (the items present in the first set that are missing in the second), while

print(set(b) - set(a)) returns {'other'}

Revje
  • 66
  • 1
  • 6
  • @random-xyz does order matter in your comparisons? How about duplicates? I recommend editing your post to show examples of what you're trying to do. – ggorlen Nov 16 '19 at 17:07