ruk·si

# 🐍 Python - Slices

Updated at 2018-06-09 17:50
``````from typing import List

numbers: List[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# index =  0  1  2  3  4  5  6  7  8

assert numbers[:2]   == [1, 2]                       # first two
assert numbers[2:]   == [3, 4, 5, 6, 7, 8, 9]        # everything after first two
assert numbers[-2:]  == [8, 9]                       # last two
assert numbers[:-2]  == [1, 2, 3, 4, 5, 6, 7]        # everything but the last two
assert numbers[1:3]  == [2, 3]                       # everything between index 1 and 3
assert numbers[::2]  == [1, 3, 5, 7, 9]              # every second item
assert numbers[::-1] == [9, 8, 7, 6, 5, 4, 3, 2, 1]  # reverse the order

# BAD old way to clear a list:
assert numbers[:]    == [1, 2, 3, 4, 5, 6, 7, 8, 9]  # returns all items
del numbers[:]
assert numbers == []
# modern Python should use numbers.clear()
``````

`[a:b:c]` is just syntactical sugar for `slice(a, b, c)`.

``````from typing import List

letters: List[str] = ['a', 'b', 'c']
assert letters[slice(None, None, -1)] == ['c', 'b', 'a']
``````

You can assign to slice to modify the original list.

``````from typing import List

numbers: List[int] = [1, 2, 3, 4]
assert numbers[1:3] == [2, 3]
numbers[1:3] = [5, 6]
assert numbers == [1, 5, 6, 4]
``````

# Source

• Python Tricks The Book, Dan Bader
• Fluent Python, Luciano Ramalho