Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - List comprehension with tuple unpack

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?

like image 751
stacksonstacks Avatar asked May 19 '16 01:05

stacksonstacks


2 Answers

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]
like image 174
Howardyan Avatar answered Sep 28 '22 06:09

Howardyan


new_list = [ [var1, var2] + list(t) for t in tuple_list ]
like image 42
stacksonstacks Avatar answered Sep 28 '22 06:09

stacksonstacks