0

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), ...]
2
  • (name, value) + extra_info(name)? Assuming extra_info returns a tuple? Commented Sep 30, 2014 at 22:27
  • @g.d.d.c Yes, extra_info returns multiple values, so they get packed into a tuple. Commented Sep 30, 2014 at 22:34

3 Answers 3

2

You have to sum lists and convert it to a tuple.

new_list = [(name, value) + extra_info(name) for name, value in old_list]
Sign up to request clarification or add additional context in comments.

1 Comment

Multiple values get returned as a tuple, and name and value are already in a tuple so I can just add the tuples. This will work perfectly for me!
2

try :

  new_list = [(name, value) + extra_info(name) for name, value in old_list]

no need for converting tuples to lists ...

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.