Search code examples
pythonlisttraversal

Python traversing two lists


I found this nice statement in a tutorial:

    for x,y in [(x,y) for x in listA for y in listB]:

Now, as for me, I understood, that that statment will traverse listA and listB and x is a value of list A and y is a value from listB. But in this example the two lists had the same length. Will this statement also give me all pairs, if one list is longer than the other, or do I have to use a different statement?

Thanks in advance.


Solution

  • The code computes the cartesian product (itertools.product), not zip as you suggested.

    For example, if the inputs are [1,2,3] and [4,5], the result is:

    (1,4)
    (1,5)
    (2,4)
    (2,5)
    (3,4)
    (3,5)
    

    For comparison, the result of zip([1,2,3], [4,5]) is:

    (1,4)
    (2,5)
    

    As you can see, zip (or itertools.izip) discards the additional items in the longer argument.

    Its variant itertools.izip_longest replaces these missing elements with an arbitrary value. For example, iterttools.izip_longest([1,2,3], [4,5], 99) returns:

    (1,4)
    (2,5)
    (3,99)