Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List Slicing with None as argument

Tags:

Via trial and error I found out that

my_list = range(10) my_list[:None] == my_list[:] 

I use this for django query sets so I can define a size or take all:

some_queryset[:length if length else None]  # @IanAuld some_queryset[:length or None]   # @Bakuriu # length works for all numbers and None if you want all elements # does not work with False of any other False values some_queryset[:length] 
  • Is this good practice to use None while slicing?
  • Can problems occur with this method in any case?
like image 602
yamm Avatar asked Jun 03 '15 14:06

yamm


People also ask

What is :: In slicing?

Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:) With this operator, one can specify where to start the slicing, where to end, and specify the step.

What does slice none do?

Above, slice(9) returns the slice object as slice(None, 9, None) , which you can pass to any iterable object to get that index portion. The slice() method can be used with string, list, tuple, set, bytes, or range. The following example fetch the portion of the list object.

When slicing in Python What does the 2 in [:: 2 specify?

Second note, when no start is defined as in A[:2] , it defaults to 0. There are two ends to the list: the beginning where index=0 (the first element) and the end where index=highest value (the last element).

Is slicing inclusive Python?

Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.


2 Answers

Yes, it is fine to use None, as its behavior is specified by the documentation:

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

Using None for one of the slice parameters is the same as omitting it.

like image 132
interjay Avatar answered Oct 12 '22 11:10

interjay


Your way is fine, but I would prefer :

some_queryset[:length] if length else some_queryset 

or

some_queryset[:length] if length else some_queryset[:] 

which are readable with less knowledge of how slicing treats these special cases.

like image 27
Emilio M Bumachar Avatar answered Oct 12 '22 09:10

Emilio M Bumachar