Search code examples
pythonlist-comprehensioniterable-unpacking

Iterate over list of tuples and unpack first elements only


Assume the following list: foo = [(1, 2, 3, 4), (5, 6, 7, 8)]

Is there a way to iterate over the list and unpack the first two elements of the inner tuple only?

This is a usual pattern: {a: b for a, b, _, _ in foo}, but this breaks if foo is modified (program change) and the tuple now contains 5 elements instead of 4 (the the list comprehension would need to be modified accordingly). I really like to name the elements instead of calling {f[0]: f[1] for f in foo}, so ideally, there would be some sort of "absorb all not unpacked variable", so one could call {a: b for a, b, absorb_rest in foo}. If that's possible, it wouldn't matter how many elements are contained in the tuple (as long as there are at least 2).


Solution

  • You can use extended iterable unpacking, where you extract the first two elements of the tuple, and ignore the rest of the elements. Note that this only works for python3

    {a:b for a, b, *c in foo}