Deelaka
Deelaka

Reputation: 13721

Merging a list with a list of lists

I have a list of lists:

[['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]

How can I merge it with a single list like:

['800','854','453']

So that the end result looks like:

[['John', 'Sergeant', '800'], ['Jack', 'Commander', '854'], ['Jill', 'Captain', '453']]

Initially I tried: zip(list_with_lists,list) but data was obfuscated

Upvotes: 5

Views: 176

Answers (3)

Kevin
Kevin

Reputation: 76254

a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
b = ['800', '854', '453']
c = [x+[y] for x,y in zip(a,b)]
print c

Result:

[['John', 'Sergeant ', '800'], ['Jack', 'Commander ', '854'], ['Jill', 'Captain ', '453']]

Upvotes: 29

Henrik
Henrik

Reputation: 4314

Solution with enumerate instead of zip:

a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
b = ['800','854','453']
c = [a[i]+[bi] for i,bi in enumerate(b)]

Using zip is definitely the more pythonic solution in this particular case. However, sometimes you want have access to indices (yes, even in Python), so it's useful to know about enumerate too.

Upvotes: 4

MakeCents
MakeCents

Reputation: 764

range instead of zip

a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
b = ['800','854','453']
c = [a[x]+[b[x]] for x in range(len(b))]
print c

or update original list:

[a[x].append(b[x]) for x in range(3)]

Upvotes: 1

Related Questions