user8371266
user8371266

Reputation:

Append list elements to the sublists of another list

I have two lists:

l1 = [[1, ['A', 'B'], 2], [3, ['D', 'E'], 4]]

&

l2 = ['C', 'F']

I'm having trouble appending the l2 elements to each sublist[1] so that I can get:

l3 = [[1, ['A', 'B', 'C'], 2], [3, ['D', 'E', 'F'], 4]]

I think I am just slightly off, but the append() method I keep trying is not working.

Upvotes: 0

Views: 168

Answers (2)

Devin
Devin

Reputation: 134

l1[0][1].insert(len(l1[0][1]), l2[0])

You can probably do it with append also, but this works just the same. It is slower. If you are worried about performance, don't use this. But for trivial tasks, it looks nice. https://docs.python.org/3/tutorial/datastructures.html

Upvotes: 0

cs95
cs95

Reputation: 402353

.append is the right way to go. Are you appending to the correct sublist? Here's one way using a loop.

In [702]: for i, l in enumerate(l1):
     ...:     l[1].append(l2[i])
     ...:     

In [703]: l1
Out[703]: [[1, ['A', 'B', 'C'], 2], [3, ['D', 'E', 'F'], 4]]

There's probably other ways to do this, but this is the simplest.

Upvotes: 3

Related Questions