2

According to Create a slice using a tuple, you can do it handy way:

>>> a = range(20)
>>> b = (5, 12)
>>> a[slice(*b)]
[5, 6, 7, 8, 9, 10, 11]

But what I need is advanced ones:

a[5:]
a[:12]
a[:]
a[-1]
a[-2:]
a[:-2]
a[::-1]

How to do it with tuple and *args?

b = (5,:)
>>  File "<ipython-input-26-c4eae928199d>", line 1
>>    b = (5,:)
>>           ^
>>SyntaxError: invalid syntax
Community
  • 1
  • 1
Bruno Gelb
  • 5,322
  • 8
  • 35
  • 50

1 Answers1

7

For options that you want to omit, replace it with None. Generally, if any option is omitted, it default to None.

So option like slice(None, None, None) is equivalent to a[::]. Also remember the start and step arguments default to None.

For. ex.

a[5:]  -> b=(5,None,None)
a[:12] -> b=(None,12)
a[:]   -> b=(None,None)

One thing to note here is, slicing is different from indexing. So you cannot use the slice built-in if you intend to index.

Bruno Gelb
  • 5,322
  • 8
  • 35
  • 50
Abhijit
  • 62,056
  • 18
  • 131
  • 204