Alex
Alex

Reputation: 17

Trying to replace a value within a list (via index) with another list in one line of code?

Python: Learning the basics here but I have 2 list and am trying to REPLACE the values of b into a specific index of a. I've tried doing a.insert(1, b), but that shifts the values to the side to insert the list.

Upvotes: 0

Views: 91

Answers (2)

mike.k
mike.k

Reputation: 3427

I'm assuming that they actually fit

a = range(10) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = range(10, 15) // [10, 11, 12, 13, 14]

Now I'll replace the last half of a with the values of b

a[5:5+len(b)] = b // [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]

5:5+len(b) produces indexes of 5:10, so 5,6,7,8,9

Upvotes: 0

Mithilesh Gupta
Mithilesh Gupta

Reputation: 2930

If you want to insert all values in b into a specifix index in a:

Just do : a[1] = b

Upvotes: 1

Related Questions