0

I'm trying to set several elements in a list with slice notation. For example, I'd like to set the 2nd and 3rd elements of a to 100 and 200, respectively:

a[1:2] = [100, 200]

but that is setting the 2nd element to 100 and inserting 200 instead of replacing the 3rd element. Is this even possible in Python (using Python 2.7 if that matters)? I could easily iterate, but I wanted a more elegant Pythonic solution (even if it might be considered less readable).

>>> a=[0]*4
>>> a
[0, 0, 0, 0]
>>> a[1:2] = [100,200]
>>> a
[0, 100, 200, 0, 0]
>>> 

1 Answers1

8

You meant to do a[1:3], not a[1:2]. Note the rules on Python slice indexing: the slice [start:end] goes from start to end-1.

a=[0]*4
a[1:3] = [100,200]
a
# [0, 100, 200, 0]
Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187