Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curious behaviour of Python lists [duplicate]

Tags:

python

list

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?

like image 858
smilingbuddha Avatar asked Oct 28 '15 23:10

smilingbuddha


People also ask

Is duplicate allowed in list Python?

Python list can contain duplicate elements.

What are duplicates in Python?

If an integer or string or any items in a list are repeated more than one time, they are duplicates.


1 Answers

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.

like image 104
tuxtimo Avatar answered Sep 22 '22 18:09

tuxtimo