Jason Pan Jason Pan - 4 months ago 20
Python Question

Is it acceptable to use a stop size larger than length of list when using colon to slice list in Python?

I want to find the first 3 elements in list by using

, but I cannot guarantee that the list will be at least length 3.

I can only find examples with given list and small stop. So, I want to know whether
is acceptable without checking the length of list.


I have tried by myself and it works well. But I want to see whether any description of doc.



>>> li=[1,2,3]

There are really only two cases to consider.

1) If a slice that extends beyond the end of the list, it will deliver the overlap of defined elements and an empty list beyond without error:

>>> li[2:]
>>> li[3:]
>>> li[5555:]
>>> li[1:55555]
[2, 3]
>>> li[555:55555]

2) Given a slice assignment, the overlapping elements are replaced and the remaining elements are appended without error:

>>> li[1:5]=[12,13,14,15,16]
>>> li
[1, 12, 13, 14, 15, 16, 15]
>>> li[555:556]=[555,556]
>>> li
[1, 12, 13, 14, 15, 16, 15, 555, 556]

The last case there, the slice assignment was to non existing elements are were therefore just appended to the existing elements.

However, if the right hand slice does not match existing elements on the left hand, there can be a ValueError for non existing elements with an extended slice (i.e., if you have list_object[start:stop:step]):

>>> li
[1, 2, 3]
>>> li[1:7:2]=range(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 4 to extended slice of size 1

But if they are existing, you can do an extended slice assignment:

>>> li=['X']*10
>>> li
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
>>> li[1:10:2]=range(5)
>>> li
['X', 0, 'X', 1, 'X', 2, 'X', 3, 'X', 4]

Most of the time -- it works as expected. If you want to use a step for assignments the elements need to be existing.