8

I have a list of tuples like: tuple_list = [ (0,1,2), (3,4,5), (6,7,8) ]

I need to create a list where each tuple is converted into a list with other static items added e.g.:

new_list = [ [var1, var2, unpack(t)] for t in tuple_list ]

How would I accomplish this in python?

asked May 19, 2016 at 1:40
2
  • Why downvote, question is legit? Commented May 19, 2016 at 2:08
  • 1
    Question is tagged py27 but in py35+ there's new unpacking in literals: [[var1, var2, *t] for t in tuple_list] Commented May 19, 2016 at 2:44

3 Answers 3

6

If your tuple is not too long, you can do:

[var1, var2, k, v, r for (k, v, r) in youList]

otherwise, write a function:

def myPack(*arg):
 return list(arg)
[myPack(var1, var2, *I) for I in youList]
answered May 19, 2016 at 2:17
Sign up to request clarification or add additional context in comments.

Comments

2
new_list = [ [var1, var2] + list(t) for t in tuple_list ]
answered May 19, 2016 at 2:11

Comments

1
new_list = [ [var1, var2] + [val for val in t] for t in tuple_list]
// => [[var1, var2, 0, 1, 2], [var1, var2, 3, 4, 5], [var1, var2, 6, 7, 8]]
answered May 19, 2016 at 1:52

1 Comment

thanks you pointed me in the right direction, it can be made more succinct by replacing the nested list comprehension with a simple list(t)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.