Paul Zet
Paul Zet

Reputation: 71

Replacing elements in a list of lists, with elements from another list

I have two lists:

abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]

I want to replace the 2nd element from each sublist of list abc with element from bbb, so I can have a list that looks like this:

[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

I know I have to use list comprehension, but I just can't figure it out.

The best I can think of is:

newlist = [i[1]=bbb for i in abc]

Upvotes: 0

Views: 30

Answers (3)

sacuL
sacuL

Reputation: 51335

This question has already been answered, but as an alternative, you could think about using numpy, especially if your arrays are large:

import numpy as np
abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]

abc = np.array(abc)
abc[:,1] = bbb

>>> abc
array([[   1,   12,  111,  111],
       [   2,   13,  222, 2222],
       [   3,   34,  333, 3333]])

# You can convert back to list too if so desired:
>>> abc.tolist()
[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could do something like this, using zip:

abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]

result = [f[:1] + [s] + f[2:] for f, s in zip(abc, bbb)]

print(result)

Output

[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can use zip:

abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]
result = [[a, b, *c] for [a, _, *c], b in zip(abc, bbb)]

Output:

[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

Upvotes: 1

Related Questions