Search code examples
pythonlistslicenonetype

Python List Slicing with None as argument


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?

Solution

  • 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.