Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing using slice() without a stop value

Tags:

python

Is there an equivalent for [:] using python's built-in slice class?

In [8]: 'abcdef'[:3]
Out[8]: 'abc'

In [9]: 'abcdef'[slice(3)]
Out[9]: 'abc'

In [10]: 'abcdef'[:]
Out[10]: 'abcdef'

In [11]: 'abcdef'[slice()]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-9afb03fec62a> in <module>()
----> 1 'abcdef'[slice()]

TypeError: slice expected at least 1 arguments, got 0
like image 283
nicoco Avatar asked Jan 28 '23 15:01

nicoco


2 Answers

You can use None, the default:

>>> 'abcdef'[:]
'abcdef'
>>> 'abcdef'[None:]
'abcdef'
>>> 'abcdef'[None:None]
'abcdef'
>>> 'abcdef'[None:None:None]
'abcdef'
>>> 'abcdef'[slice(None)]
'abcdef'
>>> 'abcdef'[slice(None, None)]
'abcdef'
>>> 'abcdef'[slice(None, None, None)]
'abcdef'
like image 181
Chris_Rands Avatar answered Jan 31 '23 03:01

Chris_Rands


Sure, any of the following would be equivalent:

>>> seq = [1,2,3,4]
>>> seq[slice(None)]
[1, 2, 3, 4]
>>> seq[slice(None, None)]
[1, 2, 3, 4]
>>> seq[slice(None, None, None)]
[1, 2, 3, 4]
like image 38
juanpa.arrivillaga Avatar answered Jan 31 '23 03:01

juanpa.arrivillaga