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]
None
while 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.
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With