9.1. Unpack Getitem
Allows to get element from ordered sequence
Works with ordered sequences:
str
,list
,tuple
Index must be
int
(positive, negative or zero)Positive Index starts with
0
Negative index starts with
-1
>>> data = ['red', 'green', 'blue']
>>>
>>> data[0]
'red'
9.1.1. Positive Index
Ascending order
Index must be less than length of an object
If index does not exist, then
IndexError
exception will be raised
SetUp:
>>> data = ['red', 'green', 'blue']
You can ask iterable about element at index,
mind that Python starts indexing from 0
:
>>> data[0]
'red'
>>>
>>> data[1]
'green'
>>>
>>> data[2]
'blue'
Index must be less than length of an object. If index does not exist,
then IndexError
exception will be raised:
>>> data[3]
Traceback (most recent call last):
IndexError: list index out of range
9.1.2. Negative Index
Descending order
Starts with
-1
Number
0
is equal to-0
Negative index starts from the end and go right to left
SetUp:
>>> data = ['red', 'green', 'blue']
Negative index starts from the end and go right to left:
>>> data[-1]
'blue'
>>>
>>> data[-2]
'green'
>>>
>>> data[-3]
'red'
Number 0
is equal to -0
:
>>> data[-0]
'red'
>>>
>>> -0 == 0
True
Index must be less than length of an object. If index does not exist,
then IndexError
exception will be raised:
>>> data[-4]
Traceback (most recent call last):
IndexError: list index out of range
9.1.3. Index Type
Index must
int
(positive, negative or zero)
SetUp:
>>> data = ['red', 'green', 'blue']
Index must int
(positive, negative or zero):
>>> data[0]
'red'
>>>
>>> data[1]
'green'
>>>
>>> data[-1]
'blue'
Any other type, even float
or str
, will not work:
>>> data[1.0]
Traceback (most recent call last):
TypeError: list indices must be integers or slices, not float
>>>
>>> data['one']
Traceback (most recent call last):
TypeError: list indices must be integers or slices, not str
9.1.4. Getitem from str
Get Item from str
:
>>> data = 'red'
>>>
>>>
>>> data[0]
'r'
>>>
>>> data[1]
'e'
>>>
>>> data[2]
'd'
>>>
>>> data[-0]
'r'
>>>
>>> data[-1]
'd'
>>>
>>> data[-2]
'e'
9.1.5. Getitem from list
Getitem from list
:
>>> data = ['red', 'green', 'blue']
Positive:
>>> data[1]
'green'
>>>
>>> data[2]
'blue'
Zero:
>>> data[0]
'red'
>>>
>>> data[-0]
'red'
Negative:
>>> data[-1]
'blue'
>>>
>>> data[-2]
'green'
>>>
>>> data[-3]
'red'
9.1.6. Getitem from tuple
Getitem from tuple
:
>>> data = ('red', 'green', 'blue')
Positive:
>>> data[1]
'green'
>>>
>>> data[2]
'blue'
Zero:
>>> data[0]
'red'
>>>
>>> data[-0]
'red'
Negative:
>>> data[-1]
'blue'
>>>
>>> data[-2]
'green'
>>>
>>> data[-3]
'red'
9.1.7. Getitem from set
Getitem from set
is impossible. set
is unordered data structure:
>>> data = {'a', 'b', 'c', 'd'}
>>>
>>>
>>> data[0]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
>>>
>>> data[1]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
>>>
>>> data[2]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
>>>
>>> data[-0]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
>>>
>>> data[-1]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
>>>
>>> data[-2]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
9.1.8. Getitem from dict
Getitem with index on
dict
is not possible
Non-integer keys:
>>> data = {'a': 0, 'b': 1, 'c': 2}
>>>
>>> data[0]
Traceback (most recent call last):
KeyError: 0
>>>
>>> data['a']
0
Integer keys:
>>> data = {0: 'a', 1: 'b', 2: 'c'}
>>>
>>> data[0]
'a'
>>>
>>> data['a']
Traceback (most recent call last):
KeyError: 'a'
>>>
>>> data[-1]
Traceback (most recent call last):
KeyError: -1
9.1.9. Getitem from list[list]
Get elements from list
of list
:
>>> data = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... ]
>>>
>>> data[0]
[1, 2, 3]
>>>
>>> data[0][1]
2
9.1.10. Getitem from list[tuple]
Get elements from list
of tuple
:
>>> data = [
... ('alice', 'secret'),
... ('bob', 'qwerty'),
... ('carol', '123456'),
... ]
>>>
>>> data[0]
('alice', 'secret')
>>>
>>> data[0][0]
'alice'
>>>
>>> data[0][0][0]
'a'
9.1.11. Getitem from list[dict]
>>> data = [
... {'username': 'alice', 'password': 'secret'},
... {'username': 'bob', 'password': 'qwerty'},
... {'username': 'carol', 'password': '123456'},
... ]
>>>
>>>
>>> data[0]
{'username': 'alice', 'password': 'secret'}
>>>
>>> data[0]['username']
'alice'
>>>
>>> data[0]['username'][0]
'a'
9.1.12. Getitem from list[Sequence]
list
of mixedSequence
, such as:list
,tuple
orstr
Get elements from list of sequences:
>>> data = [[1, 2, 3],
... (4, 5, 6),
... {7, 8, 9}]
List:
>>> data[0]
[1, 2, 3]
>>>
>>> data[0][1]
2
Tuple:
>>> data[1]
(4, 5, 6)
>>>
>>> data[1][0]
4
Set:
>>> data[2]
{8, 9, 7}
>>>
>>> data[2][0]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
9.1.13. Use Case - 1
>>> crew = {
... 0: 'alice',
... 1: 'bob',
... 2: 'carol',
... }
>>>
>>>
>>> crew[0]
'alice'
>>>
>>> crew[1]
'bob'
>>>
>>> crew[2]
'carol'
>>>
>>> crew[-0]
'alice'
>>>
>>> crew[-1]
Traceback (most recent call last):
KeyError: -1
9.1.14. Use Case - 2
>>> calendarium = {
... 1961: 'First Human Space Flight',
... 1969: 'First Step on the Moon',
... }
>>>
>>>
>>> calendarium[1961]
'First Human Space Flight'
>>>
>>> calendarium['1961']
Traceback (most recent call last):
KeyError: '1961'
9.1.15. Assignments
# %% About
# - Name: Unpack Getitem Header
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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 `result: tuple` with `DATA` header (row with index 0)
# 2. Use getitem, i.e.: `list[index]`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: tuple` z nagłówkiem `DATA` (wiersz o indeksie 0)
# 2. Użyj getitem, tj. `list[index]`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is tuple, \
'Variable `result` has invalid type, should be tuple'
>>> assert len(result) == 3, \
'Variable `result` length should be 3'
>>> result
('firstname', 'lastname', 'age')
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result: tuple[str,str,str]
# %% Data
DATA = [
('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Bob', 'Banana', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
# %% Result
result = ...
# %% About
# - Name: Unpack Getitem Positive
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% 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 `result_a: tuple` with row from `DATA` at index 2
# 2. Define `result_b: tuple` with row from `DATA` at index 4
# 3. Define `result_c: tuple` with row from `DATA` at index 6
# 4. Use getitem, i.e.: `list[index]`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result_a: tuple` z wierszem z `DATA` o indeksie 2
# 2. Zdefiniuj `result_b: tuple` z wierszem z `DATA` o indeksie 4
# 3. Zdefiniuj `result_c: tuple` z wierszem z `DATA` o indeksie 6
# 4. Użyj getitem, tj. `list[index]`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result_a is not Ellipsis, \
'Assign your result to variable `result_a`'
>>> assert type(result_a) is tuple, \
'Variable `result_a` has invalid type, should be tuple'
>>> assert len(result_a) == 3, \
'Variable `result_a` length should be 3'
>>> assert result_b is not Ellipsis, \
'Assign your result to variable `result_b`'
>>> assert type(result_b) is tuple, \
'Variable `result_b` has invalid type, should be tuple'
>>> assert len(result_b) == 3, \
'Variable `result_b` length should be 3'
>>> assert result_c is not Ellipsis, \
'Assign your result to variable `result_c`'
>>> assert type(result_c) is tuple, \
'Variable `result_c` has invalid type, should be tuple'
>>> assert len(result_c) == 3, \
'Variable `result_c` length should be 3'
>>> result_a
('Bob', 'Banana', 31)
>>> result_b
('Dave', 'Durian', 33)
>>> result_c
('Mallory', 'Melon', 15)
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result_a: tuple[str,str,int]
result_b: tuple[str,str,int]
result_c: tuple[str,str,int]
# %% Data
DATA = [
('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Bob', 'Banana', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
# %% Result
result_a = ...
result_b = ...
result_c = ...
# %% About
# - Name: Unpack Getitem Negative
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2
# %% 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 `result_a: tuple` with row from `DATA` at index -5
# 2. Define `result_b: tuple` with row from `DATA` at index -3
# 3. Define `result_c: tuple` with row from `DATA` at index -1
# 4. Use getitem, i.e.: `list[index]`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result_a: tuple` z wierszem z `DATA` o indeksie -5
# 2. Zdefiniuj `result_b: tuple` z wierszem z `DATA` o indeksie -3
# 3. Zdefiniuj `result_c: tuple` z wierszem z `DATA` o indeksie -1
# 4. Użyj getitem, tj. `list[index]`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> assert result_a is not Ellipsis, \
'Assign your result to variable `result_a`'
>>> assert type(result_a) is tuple, \
'Variable `result_a` has invalid type, should be tuple'
>>> assert len(result_a) == 3, \
'Variable `result_a` length should be 3'
>>> assert result_b is not Ellipsis, \
'Assign your result to variable `result_b`'
>>> assert type(result_b) is tuple, \
'Variable `result_b` has invalid type, should be tuple'
>>> assert len(result_b) == 3, \
'Variable `result_b` length should be 3'
>>> assert result_c is not Ellipsis, \
'Assign your result to variable `result_c`'
>>> assert type(result_c) is tuple, \
'Variable `result_c` has invalid type, should be tuple'
>>> assert len(result_c) == 3, \
'Variable `result_c` length should be 3'
>>> result_a
('Bob', 'Banana', 31)
>>> result_b
('Dave', 'Durian', 33)
>>> result_c
('Mallory', 'Melon', 15)
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
result_a: tuple[str,str,int]
result_b: tuple[str,str,int]
result_c: tuple[str,str,int]
# %% Data
DATA = [
('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Bob', 'Banana', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
# %% Result
result_a = ...
result_b = ...
result_c = ...
# %% About
# - Name: Unpack Getitem Select
# - Difficulty: easy
# - Lines: 4
# - 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 `result: list` with rows from `DATA` at indexes: 0, 1, -1
# 2. Use getitem, i.e.: `list[index]`
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: list` z wierszami z `DATA` o indeksach: 0, 1, -1
# 2. Użyj getitem, tj. `list[index]`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `list.append()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'
>>> from pprint import pprint
>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert len(result) == 3, \
'Variable `result` length should be 3'
>>> pprint(result)
[('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Mallory', 'Melon', 15)]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
type header = tuple[str,str,str]
type row = tuple[str,str,int]
result: list[header|row]
# %% Data
DATA = [
('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Bob', 'Banana', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
# %% Result
result = ...
# %% About
# - Name: Unpack Getitem Header/Data
# - Difficulty: easy
# - Lines: 11
# - 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[str]` with a header (first line of `DATA`)
# 2. Define `rows: list[tuple]` with rows (all the other lines of `DATA`)
# 3. Use getitem, i.e.: `list[index]`
# 4. Do not use slice, i.e.: `list[start:stop:step]`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `header: tuple[str]` z nagłówkiem (pierwsza linia `DATA`)
# 2. Zdefiniuj `rows: list[tuple]` z wierszami (wszystkie inne linie `DATA`)
# 3. Użyj getitem, tj. `list[index]`
# 4. Nie używaj slice, tj. `list[start:stop:step]`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `list.append()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from pprint import pprint
>>> assert header is not Ellipsis, \
'Assign your result to variable `header`'
>>> assert type(header) is tuple, \
'Variable `header` has invalid type, should be tuple'
>>> assert header not in rows, \
'Header should not be in `rows`'
>>> assert rows is not Ellipsis, \
'Assign your result to variable `rows`'
>>> assert all(type(x) is tuple for x in rows), \
'All elements in `rows` should be tuple'
>>> content = open(__file__).read()
>>> assert 'DATA'+'[1:]' not in content, \
'You should not use `slice`'
>>> assert 'DATA'+'[1:11]' not in content, \
'You should not use `slice`'
>>> pprint(header)
('firstname', 'lastname', 'age')
>>> pprint(rows)
[('Alice', 'Apricot', 30),
('Bob', 'Banana', 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 -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', 'Banana', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
# %% Result
header = ...
rows = ...