Python slice() built-in function
From the Python 3 documentation
Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop, and step which merely return the argument values (or their default).
Introduction
The slice()
function in Python returns a slice object that can be used to slice sequences like lists, tuples, or strings. A slice object represents a set of indices specified by start
, stop
, and step
.
Examples
>>> furniture = ['table', 'chair', 'rack', 'shelf']
>>> furniture[0:4]
# ['table', 'chair', 'rack', 'shelf']
>>> furniture[1:3]
# ['chair', 'rack']
>>> furniture[0:-1]
# ['table', 'chair', 'rack']
>>> furniture[:2]
# ['table', 'chair']
>>> furniture[1:]
# ['chair', 'rack', 'shelf']
>>> furniture[:]
# ['table', 'chair', 'rack', 'shelf']
Slicing the complete list will perform a copy:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam2 = spam[:]
# ['cat', 'bat', 'rat', 'elephant']
>>> spam.append('dog')
>>> spam
# ['cat', 'bat', 'rat', 'elephant', 'dog']
>>> spam2
# ['cat', 'bat', 'rat', 'elephant']