user1302074
user1302074

Reputation:

combinding a list of lists into new lists in python

I have a list of lists

list_of_lists[['front','stuff'],['back1,'stuff'],['back3','stuff'], ...['back...', 'stuff']]

I want to take the front list and append to each of the back lists:

['front','stuff','back1','stuff']
['front','stuff','back2','stuff']
['front','stuff','back3','stuff']
 ....
['front','stuff','back..','stuff']

I know I can set front = lists_of_lists[0] to get ['front','stuff']

How do I iterate and combine the front and backs, each into their own list?

Upvotes: 0

Views: 64

Answers (2)

Akavall
Akavall

Reputation: 86276

my_lists = [['front','stuff'],['back1','stuff'],['back2','stuff']]

new_list = [my_lists[0] + sublist for sublist in my_lists[1:]]

Result:

>>> new_list
[['front', 'stuff', 'back1', 'stuff'], ['front', 'stuff', 'back3', 'stuff']]

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304355

[list_of_lists[0] + i for i in list_of_lists[1:]]  

or if you want to avoid the temporary slice

front = list_of_lists[0]
[front + j for i, j in enumerate(list_of_lists) if i]  

Upvotes: 2

Related Questions