10.2. Unpack Slice — Python
Slice argument must be
int(positive, negative or zero)sequence[start:stop:step]startdefaults to0stopdefaults tolen(sequence)stepdefaults to1data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory']
10.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']
10.2.2. Step
sequence[start:stop:step]stepdefaults to1Every
n-th elementdata[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']
10.2.3. Default Start
sequence[:stop]startdefaults to0data[0:3]data[:3]
>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory'] >>> >>> data[0:3] ['Alice', 'Bob', 'Carol'] >>> >>> data[:3] ['Alice', 'Bob', 'Carol']
10.2.4. Default Stop
sequence[start:]stopdefaults tolen(sequence)data[3:6]data[3:]
>>> data = ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Mallory'] >>> >>> data[3:6] ['Dave', 'Eve', 'Mallory'] >>> >>> data[3:] ['Dave', 'Eve', 'Mallory']
10.2.5. Default Step
sequence[::step]stepdefaults to1data[::]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']
10.2.6. Default Start/Stop/Step
sequence[:]sequence[::]startdefaults to0stopdefaults tolen(sequence)stepdefaults to1data[:]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']
10.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']
10.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']
10.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:] []
10.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']
10.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
10.2.12. Slice str
>>> data = 'abcde' >>> >>> data[0:3] 'abc' >>> >>> data[-3:] 'cde' >>> >>> data[::2] 'ace'
10.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')
10.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']
10.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
10.2.16. Slice dict
Slicing on
dictis 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)
10.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
10.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.
10.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) []
10.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]
10.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 !'
10.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 `result1: str` with text 'Alice Apricot' sliced from `DATA1` # 3. Define `result2: str` with text 'Bob Blackthorn' sliced from `DATA2` # 4. Define `result3: str` with text 'Carol Corn' sliced from `DATA3` # 5. Define `result4: str` with text 'Dave Durian' sliced from `DATA4` # 6. Define `result5: str` with text 'Eve Elderberry' sliced from `DATA5` # 7. Define `result6: str` with text 'Mallory Melon' sliced from `DATA6` # 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 `result1: str` z tekstem 'Alice Apricot' wyciętym z `DATA1` # 3. Define `result2: str` z tekstem 'Bob Blackthorn' wyciętym z `DATA2` # 4. Define `result3: str` z tekstem 'Carol Corn' wyciętym z `DATA3` # 5. Define `result4: str` z tekstem 'Dave Durian' wyciętym z `DATA4` # 6. Define `result5: str` z tekstem 'Eve Elderberry' wyciętym z `DATA5` # 7. Define `result6: str` z tekstem 'Mallory Melon' wyciętym z `DATA6` # 8. Użyj `slice` to wycięcia tekstu # 10. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result1 # 'Alice Apricot' # # >>> result2 # 'Bob Blackthorn' # # >>> result3 # 'Carol Corn' # # >>> result4 # 'Dave Durian' # # >>> result5 # 'Eve Elderberry' # # >>> result6 # '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 'result1' in globals(), \ 'Variable `result1` is not defined; assign result of your program to it.' >>> assert result1 is not Ellipsis, \ 'Variable `result1` has an invalid value; assign result of your program to it.' >>> assert type(result1) is str, \ 'Variable `result1` has an invalid type; expected: `str`.' >>> result1 'Alice Apricot' >>> assert 'result2' in globals(), \ 'Variable `result2` is not defined; assign result of your program to it.' >>> assert result2 is not Ellipsis, \ 'Variable `result2` has an invalid value; assign result of your program to it.' >>> assert type(result2) is str, \ 'Variable `result2` has an invalid type; expected: `str`.' >>> result2 'Bob Blackthorn' >>> assert 'result3' in globals(), \ 'Variable `result3` is not defined; assign result of your program to it.' >>> assert result3 is not Ellipsis, \ 'Variable `result3` has an invalid value; assign result of your program to it.' >>> assert type(result3) is str, \ 'Variable `result3` has an invalid type; expected: `str`.' >>> result3 'Carol Corn' >>> assert 'result4' in globals(), \ 'Variable `result4` is not defined; assign result of your program to it.' >>> assert result4 is not Ellipsis, \ 'Variable `result4` has an invalid value; assign result of your program to it.' >>> assert type(result4) is str, \ 'Variable `result4` has an invalid type; expected: `str`.' >>> result4 'Dave Durian' >>> assert 'result5' in globals(), \ 'Variable `result5` is not defined; assign result of your program to it.' >>> assert result5 is not Ellipsis, \ 'Variable `result5` has an invalid value; assign result of your program to it.' >>> assert type(result5) is str, \ 'Variable `result5` has an invalid type; expected: `str`.' >>> result5 'Eve Elderberry' >>> assert 'result6' in globals(), \ 'Variable `result6` is not defined; assign result of your program to it.' >>> assert result6 is not Ellipsis, \ 'Variable `result6` has an invalid value; assign result of your program to it.' >>> assert type(result6) is str, \ 'Variable `result6` has an invalid type; expected: `str`.' >>> result6 '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 result1: str result2: str result3: str result4: str result5: str result6: str # %% Data EXAMPLE = 'lt. John Doe, PhD' example = EXAMPLE[4:-5] # 'John Doe' DATA1 = 'prof. Alice Apricot' DATA2 = 'Bob Blackthorn, PhD' DATA3 = 'lt. col. Carol Corn, PhD-MD' DATA4 = 'Dave Durian\t' DATA5 = 'Eve Elderberry😐' DATA6 = 'Mallory Melon\U0001F610' # %% Result result1 = ... result2 = ... result3 = ... result4 = ... result5 = ... result6 = ...
# %% 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 = ...