Iterate over list of tuples and unpack first elements only

Viewed 2995

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).

4 Answers

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}                                                                                                                                                             

You can use extended iterable unpacking, keeping in this way the first two values from the iterable and ignoring the rest:

{a: b for a, b, *_ in foo}
# {1: 2, 5: 6}

Try this :

dict_ = {a:b for a,b, *_ in foo}

Output :

{1: 2, 5: 6}

If foo is changed to [(1, 2, 3, 4,9,0), (5, 6, 7, 8, 11, 16)] by program later, dict_ still remains : {1: 2, 5: 6}

use lambda

foo = [(1, 2, 3, 4), (5, 6, 7, 8)]
output = list(map(lambda x:{x[0]:x[1]}, foo))
print(output)

output

[{1: 2}, {5: 6}]
Related