9.2. Unpack Slice

  • Slice argument must be int (positive, negative or zero)

  • sequence[start:stop:step]

  • start defaults to 0

  • stop defaults to len(sequence)

  • step defaults to 1

  • data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']

9.2.1. Slice Forwards

  • sequence[start:stop]

  • data[0:3]

  • data[3:6]

  • data[1:5]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[0:3]
['Alice', 'Bob', 'Carol']
>>>
>>> data[3:6]
['Dave', 'Eve', 'Mallory']
>>>
>>> data[1:5]
['Bob', 'Carol', 'Dave', 'Eve']

9.2.2. Step

  • sequence[start:stop:step]

  • step defaults to 1

  • Every n-th element

  • data[0:6]

  • data[0:6:1]

  • data[0:6:2]

  • data[0:6:3]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[0:6]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[0:6:1]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[0:6:2]
['Alice', 'Carol', 'Eve']
>>>
>>> data[0:6:3]
['Alice', 'Dave']

9.2.3. Default Start

  • sequence[:stop]

  • start defaults to 0

  • data[0:3]

  • data[:3]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[0:3]
['Alice', 'Bob', 'Carol']
>>>
>>> data[:3]
['Alice', 'Bob', 'Carol']

9.2.4. Default Stop

  • sequence[start:]

  • stop defaults to len(sequence)

  • data[3:6]

  • data[3:]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[3:6]
['Dave', 'Eve', 'Mallory']
>>>
>>> data[3:]
['Dave', 'Eve', 'Mallory']

9.2.5. Default Step

  • sequence[::step]

  • step defaults to 1

  • data[::]

  • data[::1]

  • data[::2]

  • data[::3]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[::]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[::1]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[::2]
['Alice', 'Carol', 'Eve']
>>>
>>> data[::3]
['Alice', 'Dave']

9.2.6. Default Start/Stop/Step

  • sequence[:]

  • sequence[::]

  • start defaults to 0

  • stop defaults to len(sequence)

  • step defaults to 1

  • data[:]

  • data[::]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[:]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[::]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']

9.2.7. Slice Backwards

  • Negative index starts from the end and go right to left

  • data[:-3]

  • data[-3:]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[:-3]
['Alice', 'Bob', 'Carol']
>>>
>>> data[-3:]
['Dave', 'Eve', 'Mallory']

9.2.8. Step Backwards

  • data[6:0:-1]

  • data[::-1]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[6:0:-1]
['Mallory', 'Eve', 'Dave', 'Carol', 'Bob']
>>>
>>> data[::-1]
['Mallory', 'Eve', 'Dave', 'Carol', 'Bob', 'Alice']

9.2.9. Out of Range

  • data[:100]

  • data[100:]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[:100]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[100:]
[]

9.2.10. Index Arithmetic

  • data[start:stop:step]

  • data[start+1:stop-1:step]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> start = 0
>>> stop = len(data)
>>> step = 1
>>>
>>> data[start:stop:step]
['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[start+1:stop-1:step+1]
['Bob', 'Dave']

9.2.11. Slice Errors

  • data[1.0:]

  • data['Alice':'Mallory']

  • data[::0]

>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
>>>
>>> data[1.0:]
Traceback (most recent call last):
TypeError: slice indices must be integers or None or have an __index__ method
>>>
>>> data['Alice':'Mallory']
Traceback (most recent call last):
TypeError: slice indices must be integers or None or have an __index__ method
>>>
>>> data[::0]
Traceback (most recent call last):
ValueError: slice step cannot be zero

9.2.12. Slice str

>>> data = 'abcde'
>>>
>>> data[0:3]
'abc'
>>>
>>> data[-3:]
'cde'
>>>
>>> data[::2]
'ace'

9.2.13. Slice tuple

>>> data = ('a', 'b', 'c', 'd', 'e')
... #        0    1    2    3    4
... #       -5   -4   -3   -2   -1
>>>
>>> data[0:3]
('a', 'b', 'c')
>>>
>>> data[-3:]
('c', 'd', 'e')
>>>
>>> data[::2]
('a', 'c', 'e')

9.2.14. Slice list

>>> data = ['a', 'b', 'c', 'd', 'e']
... #        0    1    2    3    4
... #       -5   -4   -3   -2   -1
>>>
>>> data[0:3]
['a', 'b', 'c']
>>>
>>> data[-3:]
['c', 'd', 'e']
>>>
>>> data[::2]
['a', 'c', 'e']

9.2.15. Slice set

Slicing set is not possible:

>>> data = {'a', 'b', 'c', 'd', 'e'}
... #        0    1    2    3    4
... #       -5   -4   -3   -2   -1
>>>
>>> data[0:3]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable

9.2.16. Slice dict

  • Slicing on dict is not possible

>>> data = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> data[0:3]
Traceback (most recent call last):
KeyError: slice(0, 3, None)
>>>
>>> data['a':'d']
Traceback (most recent call last):
KeyError: slice('a', 'd', None)

9.2.17. Nested Sequences

>>> data = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9]
... ]
>>>
>>> data[:2]
[[1, 2, 3], [4, 5, 6]]
>>>
>>> data[:2][1:]
[[4, 5, 6]]
>>>
>>> data[:2][1:][0]
[4, 5, 6]
>>>
>>> data[:2][1:][0][1:]
[5, 6]
>>>
>>> data[:2][1:][0][1:][1]
6

9.2.18. Column Selection

Column selection unfortunately does not work on list:

>>> data = [[1, 2, 3],
...         [4, 5, 6],
...         [7, 8, 9]]
>>>
>>> data[:]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>
>>> data[:][1]
[4, 5, 6]
>>>
>>> data[:, 1]
Traceback (most recent call last):
TypeError: list indices must be integers or slices, not tuple

However this syntax is valid in numpy and pandas.

9.2.19. Use Case - 1

>>> from pprint import pprint
>>>
>>>
>>> DATA = [
...     ('firstname', 'lastname', 'age'),
...     ('Alice', 'Apricot', 30),
...     ('Bob', 'Blackthorn', 31),
...     ('Carol', 'Corn', 32),
...     ('Dave', 'Durian', 33),
...     ('Eve', 'Elderberry', 34),
...     ('Mallory', 'Melon', 15),
... ]
>>>
>>>
>>> pprint(DATA[1:], width=30)
[('Alice', 'Apricot', 30),
 ('Bob', 'Blackthorn', 31),
 ('Carol', 'Corn', 32),
 ('Dave', 'Durian', 33),
 ('Eve', 'Elderberry', 34),
 ('Mallory', 'Melon', 15)]
>>>
>>> pprint(DATA[1::2], width=30)
[('Alice', 'Apricot', 30),
 ('Carol', 'Corn', 32),
 ('Eve', 'Elderberry', 34)]
>>>
>>> pprint(DATA[1::-2], width=30)
[('Alice', 'Apricot', 30)]
>>>
>>> pprint(DATA[:1:-2], width=30)
[('Mallory', 'Melon', 15),
 ('Dave', 'Durian', 33),
 ('Bob', 'Blackthorn', 31)]
>>>
>>> pprint(DATA[:-5:-2], width=30)
[('Mallory', 'Melon', 15),
 ('Dave', 'Durian', 33)]
>>>
>>> pprint(DATA[1:-5:-2], width=30)
[]

9.2.20. Use Case - 2

>>> data = [[1, 2, 3],
...         [4, 5, 6],
...         [7, 8, 9]]
>>>
>>> data[::2]
[[1, 2, 3],
 [7, 8, 9]]
>>>
>>> data[::2][1]
[7, 8, 9]
>>>
>>> data[::2][:1]
[[1, 2, 3]]
>>>
>>> data[::2][1][1:]
[8, 9]

9.2.21. Use Case - 3

>>> text = 'We choose to go to the Moon!'
>>> word = 'Moon'
>>>
>>>
>>> start = text.find(word)
>>> stop = start + len(word)
>>>
>>> text[start:stop]
'Moon'
>>>
>>> text[:start]
'We choose to go to the '
>>>
>>> text[stop:]
'!'
>>>
>>> text[:start] + text[stop:]
'We choose to go to the !'

9.2.22. Assignments

# %% About
# - Name: Unpack Slice Text
# - Difficulty: easy
# - Lines: 6
# - Minutes: 8

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. From each `DATA_*` variable remove scientific title, military rank, etc.
# 2. Define `result_a: str` with text 'Alice Apricot' sliced from `DATA_A`
# 3. Define `result_b: str` with text 'Bob Blackthorn' sliced from `DATA_B`
# 4. Define `result_c: str` with text 'Carol Corn' sliced from `DATA_C`
# 5. Define `result_d: str` with text 'Dave Durian' sliced from `DATA_D`
# 6. Define `result_e: str` with text 'Eve Elderberry' sliced from `DATA_E`
# 7. Define `result_f: str` with text 'Mallory Melon' sliced from `DATA_F`
# 8. Use `slice` to extract text
# 10. Run doctests - all must succeed

# %% Polish
# 1. Z każdej zmiennej `DATA_*` usuń tytuł naukowy i stopnia wojskowego
# 2. Define `result_a: str` z tekstem 'Alice Apricot' wyciętym z `DATA_A`
# 3. Define `result_b: str` z tekstem 'Bob Blackthorn' wyciętym z `DATA_B`
# 4. Define `result_c: str` z tekstem 'Carol Corn' wyciętym z `DATA_C`
# 5. Define `result_d: str` z tekstem 'Dave Durian' wyciętym z `DATA_D`
# 6. Define `result_e: str` z tekstem 'Eve Elderberry' wyciętym z `DATA_E`
# 7. Define `result_f: str` z tekstem 'Mallory Melon' wyciętym z `DATA_F`
# 8. Użyj `slice` to wycięcia tekstu
# 10. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result_a
# 'Alice Apricot'
#
# >>> result_b
# 'Bob Blackthorn'
#
# >>> result_c
# 'Carol Corn'
#
# >>> result_d
# 'Dave Durian'
#
# >>> result_e
# 'Eve Elderberry'
#
# >>> result_f
# 'Mallory Melon'

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> assert result_a is not Ellipsis, \
'Variable `result_a` has an invalid value; assign result of your program to it.'
>>> assert type(result_a) is str, \
'Variable `result_a` has an invalid type; expected: `str`.'
>>> result_a
'Alice Apricot'

>>> assert result_b is not Ellipsis, \
'Variable `result_b` has an invalid value; assign result of your program to it.'
>>> assert type(result_b) is str, \
'Variable `result_b` has an invalid type; expected: `str`.'
>>> result_b
'Bob Blackthorn'

>>> assert result_c is not Ellipsis, \
'Variable `result_c` has an invalid value; assign result of your program to it.'
>>> assert type(result_c) is str, \
'Variable `result_c` has an invalid type; expected: `str`.'
>>> result_c
'Carol Corn'

>>> assert result_d is not Ellipsis, \
'Variable `result_d` has an invalid value; assign result of your program to it.'
>>> assert type(result_d) is str, \
'Variable `result_d` has an invalid type; expected: `str`.'
>>> result_d
'Dave Durian'

>>> assert result_e is not Ellipsis, \
'Variable `result_e` has an invalid value; assign result of your program to it.'
>>> assert type(result_e) is str, \
'Variable `result_e` has an invalid type; expected: `str`.'
>>> result_e
'Eve Elderberry'

>>> assert result_f is not Ellipsis, \
'Variable `result_f` has an invalid value; assign result of your program to it.'
>>> assert type(result_f) is str, \
'Variable `result_f` has an invalid type; expected: `str`.'
>>> result_f
'Mallory Melon'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
result_a: str
result_b: str
result_c: str
result_d: str
result_e: str
result_f: str

# %% Data
EXAMPLE = 'lt. John Doe, PhD'
example = EXAMPLE[4:-5]
# 'John Doe'

DATA_A = 'prof. Alice Apricot'
DATA_B = 'Bob Blackthorn, PhD'
DATA_C = 'lt. col. Carol Corn, PhD-MD'
DATA_D = 'Dave Durian\t'
DATA_E = 'Eve Elderberry😐'
DATA_F = 'Mallory Melon\U0001F610'

# %% Result
result_a = ...
result_b = ...
result_c = ...
result_d = ...
result_e = ...
result_f = ...

# %% About
# - Name: Unpack Slice Header/Rows
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define `header: tuple` with a header (first line of `DATA`)
# 2. Define `rows: list` with rows (all the other lines of `DATA`)
# 3. Use slice, i.e.: `list[start:stop:step]`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `header: tuple` z nagłówkiem (pierwsza linia `DATA`)
# 2. Zdefiniuj `rows: list` z wierszami (wszystkie inne linie `DATA`)
# 3. Użyj slice, tj. `list[start:stop:step]`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> header
# ('firstname', 'lastname', 'age')
#
# >>> rows
# [('Alice', 'Apricot', 30),
#  ('Bob', 'Blackthorn', 31),
#  ('Carol', 'Corn', 32),
#  ('Dave', 'Durian', 33),
#  ('Eve', 'Elderberry', 34),
#  ('Mallory', 'Melon', 15)]

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> from pprint import pprint

>>> assert header is not Ellipsis, \
'Variable `header` has an invalid value; assign result of your program to it.'
>>> assert type(header) is tuple, \
'Variable `header` has an invalid type; expected: `tuple`.'
>>> pprint(header)
('firstname', 'lastname', 'age')

>>> assert rows is not Ellipsis, \
'Variable `rows` has an invalid value; assign result of your program to it.'
>>> assert all(type(x) is tuple for x in rows), \
'Variable `rows` has elements of an invalid type; all items should be: `tuple`.'
>>> assert header not in rows, \
'Header should not be in `rows`'
>>> pprint(rows)
[('Alice', 'Apricot', 30),
 ('Bob', 'Blackthorn', 31),
 ('Carol', 'Corn', 32),
 ('Dave', 'Durian', 33),
 ('Eve', 'Elderberry', 34),
 ('Mallory', 'Melon', 15)]
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports

# %% Types
header = tuple[str,str,str]
rows = list[tuple[str,str,int]]

# %% Data
DATA = [
    ('firstname', 'lastname', 'age'),
    ('Alice', 'Apricot', 30),
    ('Bob', 'Blackthorn', 31),
    ('Carol', 'Corn', 32),
    ('Dave', 'Durian', 33),
    ('Eve', 'Elderberry', 34),
    ('Mallory', 'Melon', 15),
]

# %% Result
header = ...
rows = ...