I want to find the first 3 elements in list by using
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
>>> 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.