Reputation: 7146
I have a list of tuples, and I need to add more information to each tuple. The list looks something like this:
[(name1, value1), (name2, value2), (name1, value3), ...]
I have a function to get the extra information for each tuple, but I need the new tuples to be flat and I can't think of a good way to do that in a list comprehension. I would love to be able to do something like this:
new_list = [(name, value, *extra_info(name)) for name, value in old_list]
or
new_list = [list(name, value, *extra_info(name)) for name, value in old_list]
Unfortunately the first one is bad syntax, and the second one doesn't work because list
only takes in one argument. Is there a way to unpack the tuple returned by extra_info
in a list comprehension? Failing that, what would be the most Pythonic way to tackle this problem?
To be clear, I want to end up with a list that looks like this:
[(name1, value1, extra1, extra2), (name2, value2, extra3, extra4), (name1, value3, extra1, extra2), ...]
Upvotes: 0
Views: 118
Reputation: 7146
Something I came up with while thinking about this was to use a lambda echo function to pack the new tuples:
packer = lambda *x: x
new_list = [packer(name, value, *extra_info(name)) for name, value in old_list]
Upvotes: 0
Reputation: 4987
You have to sum lists and convert it to a tuple.
new_list = [(name, value) + extra_info(name) for name, value in old_list]
Upvotes: 2
Reputation: 9704
try :
new_list = [(name, value) + extra_info(name) for name, value in old_list]
no need for converting tuples to lists ...
Upvotes: 2