Iago Álvarez
Iago Álvarez

Reputation: 1

How can I insert a position of a list in another list in python?

I have three lists in python. I want to insert in the last one in the parameter of the position the value of the first and in the parameter of value the value of the second one. This is my code:

list1 = [0, 1, 2, 3, 4, 6, 9, 5, 7, 8]
list2 = [0, 1, 2, 2, 2, 2, 2, 3, 4, 5]
list3 = [0]*len(list1)
for i in range(len(list1)):
    list3.insert(list1[i],list2[i])

With this I obtain list3 with a length of 20, not 10 and list3 has to be like this: [0,1,2,2,2,3,2,4,5,2]. How can I solve this??

Upvotes: 0

Views: 54

Answers (1)

lroth
lroth

Reputation: 367

we can use zip function to get list1 and list2 together:

list1 = [0, 1, 2, 3, 4, 6, 9, 5, 7, 8]
list2 = [0, 1, 2, 2, 2, 2, 2, 3, 4, 5]
list3 = [0]*len(list1)

for index, value in zip(list1, list2):
    list3[index] = value
print(list3)

Result:

[0, 1, 2, 2, 2, 3, 2, 4, 5, 2]

Upvotes: 1

Related Questions