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?
Python list can contain duplicate elements.
If an integer or string or any items in a list are repeated more than one time, they are duplicates.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With