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
stacksonstacks
9,4716 gold badges30 silver badges45 bronze badges
3 Answers 3
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
Howardyan
6671 gold badge6 silver badges15 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
new_list = [ [var1, var2] + list(t) for t in tuple_list ]
answered May 19, 2016 at 2:11
stacksonstacks
9,4716 gold badges30 silver badges45 bronze badges
Comments
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
T. Claverie
12.4k1 gold badge19 silver badges29 bronze badges
1 Comment
stacksonstacks
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)Explore related questions
See similar questions with these tags.
lang-py
[[var1, var2, *t] for t in tuple_list]