1

I just noticed a behaviour in python I don't understand.
Imagine the following code:

myArray  = [0] * 10   
myTuple = (1,1)

Now I want to assign the two values in my tuple to two fields in my array. Since Python allows to change muliple values at once I tried

myArray[2:3] = myTuple

What I expect for myArray is

[0,0,1,1,0,0,0,0,0,0]

But what I actually get is

[0,0,1,1,0,0,0,0,0,0,0]

Who can explain this behaviour to me?

Holloway
  • 6,412
  • 1
  • 26
  • 33
0xAffe
  • 1,156
  • 1
  • 13
  • 29
  • 4
    what you mean is probably: `myArray[2:4] = myTuple`. – hiro protagonist Sep 29 '15 at 11:16
  • Check also [http://stackoverflow.com/questions/509211/explain-pythons-slice-notation](http://stackoverflow.com/q/509211/2314737) – user2314737 Sep 29 '15 at 11:18
  • It's not wholly clear whether what's surprising you is that: 1. slice assignment can change the length of a list; or: 2. `[2:3]` only slices a single element. Both are already explained elsewhere, though. – jonrsharpe Sep 29 '15 at 11:21

2 Answers2

5

The issue is that the length of the slice [2:3] is 1, the element at index 2 (slicing in Python is exclusive of the stop index, so element at index 3 is not included). And you are trying to insert 2 elements in it, hence it inserts the second element after index 2, increasing the size of the array by 1. You need to do -

myArray[2:4] = myTuple

Demo -

>>> myArray  = [0] * 10
>>> myTuple = (1,1)
>>> myArray[2:3] = myTuple
>>> len(myArray)
11
>>> myArray  = [0] * 10
>>> myTuple = (1,1)
>>> myArray[2:4] = myTuple
>>> len(myArray)
10
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
2

myArray[2:3] is actually a list containing one element (which is the third element in the list).

You're simply inserting 2 elements there, and that's increases the list's size. You probably want to do:

myArray[2:4] = myTuple
Maroun
  • 94,125
  • 30
  • 188
  • 241