>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
Negative values also work to make a copyofthe same listinreverse order:
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
This also works for tuples, arrays, and strings:
>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'
>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]
Extended slices aren't this flexible. When assigning to an extended slice, thelistonthe right hand side ofthe statement must containthe same numberof items asthe slice itis replacing:
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3to extended slice of size 2
Deletion is more straightforward:
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]
One can also now pass slice objects tothe __getitem__ methods ofthe built-in sequences:
>>> range(10).__getitem__(slice(0, 5, 2))
[0, 2, 4]
Or use slice objects directly in subscripts:
>>> range(10)[slice(0, 5, 2)]
[0, 2, 4]