6

How come this code does not throw an error when run by the Python interpreter.

a = ['A', 'B', 'C']
a[20:] = ['D', 'E']
print a

Output is ['A', 'B', 'C', 'D', 'E']. I thought Python would give me an error on the second statement since a has only 3 elements. Does this feature have any natural uses while coding?

smilingbuddha
  • 14,334
  • 33
  • 112
  • 189
  • 1
    This makes a lot less sense than reading `a[20:]`. Pretty odd that `assert ['D', 'E'] == a[20:]` will fail here – Eric Oct 28 '15 at 23:36
  • 1
    This makes sense with the way slice indexing works. Since `a[3:] == a[20:]`, it follows that due to the internal implementation at C level that it would simply append elements if null or overwrite the selected range. – Richard Kenneth Niescior Oct 28 '15 at 23:42
  • @Eric: `a[20:]` will just return an empty list. – tuxtimo Oct 28 '15 at 23:43
  • @tuxtimo: Indeed. My point is that it strikes me as incorrect behavour that the following behaves as it does `a[:20] = x; assert a[:20] == x` – Eric Oct 28 '15 at 23:46
  • @Eric at the first look = Yes. If you look closer: The assignment with the slicing, as said, does no boundary checks so it just appends the item(s) to the list (that's how it works and I do not know the exact impl details). What I can say is, that the values are NOT inserted at the beginning of the slicing instead of the end of the list. So you cannot access them at the position you've expected. – tuxtimo Oct 28 '15 at 23:50

1 Answers1

4

That's how python works. In python for slicing no boundary checks will take place. It just expands your list since it is a mutable object.

It's also interesting when you are reading out of boundaries with slicing:

f = a[20:]

f will be an empty list.

tuxtimo
  • 2,730
  • 20
  • 29