Reputation: 1972
I am trying to put the elements in list2
inside each of the nested lists in list1
. This is what I have tried so far:
list_1 = [[0, 1], [1, 4], [2, 3]]
list_2 = [100, 100, 100]
store_1 = []
for x in list_1:
for y in list_2:
x.append(y)
store_1.append(x)
print(store_1)
But the output is:
[[0, 1, 100, 100, 100], [0, 1, 100, 100, 100], [0, 1, 100, 100, 100], [1, 4, 100, 100, 100], [1, 4, 100, 100, 100], [1, 4, 100, 100, 100], [2, 3, 100, 100, 100], [2, 3, 100, 100, 100], [2, 3, 100, 100, 100]]
The output should be like this:
[[0,1,100],[1,4,100], [2,3,100]]
How can i fix my code to get the desired output?
Upvotes: 2
Views: 66
Reputation: 740
Without using zip
list_1 = [[0, 1], [1, 4], [2, 3]]
list_2 = [100, 100, 100]
[list_1[idx] + [x] for idx, x in enumerate(list_2)]
> [[0, 1, 100], [1, 4, 100], [2, 3, 100]]
Upvotes: 1
Reputation: 82765
Using zip
Ex:
list_1 = [[0, 1], [1, 4], [2, 3]]
list_2 = [100, 100, 100]
store_1 = [x + [y] for x, y in zip(list_1, list_2)]
print(store_1)
Output:
[[0, 1, 100], [1, 4, 100], [2, 3, 100]]
Upvotes: 5