Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 my_list[:3], 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 my_list[:3] is acceptable without checking the length of list.

Thanks!

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

like image 692
Jason Pan Avatar asked Nov 14 '16 02:11

Jason Pan


2 Answers

Given:

>>> 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:]
[3]
>>> 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.

like image 96
dawg Avatar answered Nov 02 '22 04:11

dawg


This is fine regardless of the length of the list.

This is the behavior of the call you're trying to make:

a = [1,2,3,4]
b = [1,2]
a[:3]
>>>[1,2,3]
b[:3]
>>>[1,2]

Essentially it will behave exactly as you want to.

like image 21
Irteza Farhat Avatar answered Nov 02 '22 03:11

Irteza Farhat