10.1. Unpack Getitem
Get item from ordered sequence
Works with ordered sequences:
str,list,tupleIndex must be
int(positive, negative or zero)Positive Index starts with
0Negative index starts with
-1
>>> data = ['Alice', 'Bob', 'Carol']
>>>
>>> data[0]
'Alice'
10.1.1. Positive Index
Ascending order
Index must be less than length of an object
If index does not exist, then
IndexErrorexception will be raised
SetUp:
>>> data = ['Alice', 'Bob', 'Carol']
You can ask iterable about element at index,
mind that Python starts indexing from 0:
>>> data[0]
'Alice'
>>>
>>> data[1]
'Bob'
>>>
>>> data[2]
'Carol'
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
10.1.2. Negative Index
Descending order
Starts with
-1Number
0is equal to-0Negative index starts from the end and go right to left
SetUp:
>>> data = ['Alice', 'Bob', 'Carol']
Negative index starts from the end and go right to left:
>>> data[-1]
'Carol'
>>>
>>> data[-2]
'Bob'
>>>
>>> data[-3]
'Alice'
Number 0 is equal to -0:
>>> data[-0]
'Alice'
>>>
>>> -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
10.1.3. Index Type
Index must
int(positive, negative or zero)
SetUp:
>>> data = ['Alice', 'Bob', 'Carol']
Index must int (positive, negative or zero):
>>> data[0]
'Alice'
>>>
>>> data[1]
'Bob'
>>>
>>> data[-1]
'Carol'
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
10.1.4. Getitem from str
Get Item from str:
>>> data = 'Alice'
Positive index:
>>> data[1]
'l'
>>>
>>> data[2]
'i'
Zero index:
>>> data[0]
'A'
>>>
>>> data[-0]
'A'
Negative index:
>>> data[-1]
'e'
>>>
>>> data[-2]
'c'
10.1.5. Getitem from list
Getitem from list:
>>> data = ['Alice', 'Bob', 'Carol']
Positive index:
>>> data[1]
'Bob'
>>>
>>> data[2]
'Carol'
Zero index:
>>> data[0]
'Alice'
>>>
>>> data[-0]
'Alice'
Negative index:
>>> data[-1]
'Carol'
>>>
>>> data[-2]
'Bob'
>>>
>>> data[-3]
'Alice'
10.1.6. Getitem from tuple
Getitem from tuple:
>>> data = ('Alice', 'Bob', 'Carol')
Positive index:
>>> data[1]
'Bob'
>>>
>>> data[2]
'Carol'
Zero index:
>>> data[0]
'Alice'
>>>
>>> data[-0]
'Alice'
Negative index:
>>> data[-1]
'Carol'
>>>
>>> data[-2]
'Bob'
>>>
>>> data[-3]
'Alice'
10.1.7. Getitem from set
Getitem from set is impossible. set is unordered data structure:
>>> data = {'Alice', 'Bob', 'Carol'}
Positive index:
>>> 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
Zero index:
>>> data[0]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
>>>
>>> data[-0]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
Negative index:
>>> 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
10.1.8. Getitem from dict
Getitem with index on
dictis not possible
Non-integer keys:
>>> data = {'Alice': 0, 'Bob': 1, 'Carol': 2}
>>>
>>>
>>> data['Alice']
0
>>>
>>> data[0]
Traceback (most recent call last):
KeyError: 0
Integer keys:
>>> data = {0: 'Alice', 1: 'Bob', 2: 'Carol'}
>>>
>>>
>>> data['Alice']
Traceback (most recent call last):
KeyError: 'Alice'
>>>
>>> data[0]
'Alice'
>>>
>>> data[-1]
Traceback (most recent call last):
KeyError: -1
10.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
10.1.10. Getitem from list[tuple]
Get elements from list of tuple:
>>> data = [
... ('Alice', 'Apricot'),
... ('Bob', 'Blackthorn'),
... ('Carol', 'Corn'),
... ]
>>>
>>> data[0]
('Alice', 'Apricot')
>>>
>>> data[0][0]
'Alice'
>>>
>>> data[0][0][0]
'A'
10.1.11. Getitem from list[dict]
>>> data = [
... {'firstname': 'Alice', 'lastname': 'Apricot'},
... {'firstname': 'Bob', 'lastname': 'Blackthorn'},
... {'firstname': 'Carol', 'lastname': 'Corn'},
... ]
>>>
>>>
>>> data[0]
{'firstname': 'Alice', 'lastname': 'Apricot'}
>>>
>>> data[0]['firstname']
'Alice'
>>>
>>> data[0]['firstname'][0]
'A'
10.1.12. Getitem from list[Sequence]
listof mixedSequence, such as:list,tupleorstr
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
10.1.13. Use Case - 1
>>> ranking = {
... 0: 'Alice',
... 1: 'Bob',
... 2: 'Carol',
... }
>>>
>>>
>>> ranking[0]
'Alice'
>>>
>>> ranking[1]
'Bob'
>>>
>>> ranking[2]
'Carol'
>>>
>>> ranking[-0]
'Alice'
>>>
>>> ranking[-1]
Traceback (most recent call last):
KeyError: -1
10.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'
10.1.15. Recap
Get item from ordered sequence
Works with ordered sequences:
str,list,tupleIndex must be
int(positive, negative or zero)Positive Index starts with
0Negative index starts with
-1
>>> data = ['Alice', 'Bob', 'Carol']
>>>
>>> data[0]
'Alice'
>>>
>>> data[-1]
'Carol'
10.1.16. 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ść
# %% Expected
# >>> result
# ('firstname', 'lastname', 'age')
# %% 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' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is tuple, \
'Variable `result` has an invalid type; expected: `tuple`.'
>>> assert len(result) == 3, \
'Variable `result` has an invalid length; expected: `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 -f -v myfile.py`
# %% Imports
# %% Types
result: tuple[str,str,str] | 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
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 `result1: tuple` with row from `DATA` at index 2
# 2. Define `result2: tuple` with row from `DATA` at index 4
# 3. Define `result3: tuple` with row from `DATA` at index 6
# 4. Use getitem, i.e.: `list[index]`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result1: tuple` z wierszem z `DATA` o indeksie 2
# 2. Zdefiniuj `result2: tuple` z wierszem z `DATA` o indeksie 4
# 3. Zdefiniuj `result3: tuple` z wierszem z `DATA` o indeksie 6
# 4. Użyj getitem, tj. `list[index]`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result1
# ('Bob', 'Blackthorn', 31)
#
# >>> result2
# ('Dave', 'Durian', 33)
#
# >>> result3
# ('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.'
>>> 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 tuple, \
'Variable `result1` has an invalid type; expected: `tuple`.'
>>> assert len(result1) == 3, \
'Variable `result1` has an invalid length; expected: `3`.'
>>> 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 tuple, \
'Variable `result2` has an invalid type; expected: `tuple`.'
>>> assert len(result2) == 3, \
'Variable `result2` has an invalid length; expected: `3`.'
>>> 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 tuple, \
'Variable `result3` has an invalid type; expected: `tuple`.'
>>> assert len(result3) == 3, \
'Variable `result3` has an invalid length; expected: `3`.'
>>> result1
('Bob', 'Blackthorn', 31)
>>> result2
('Dave', 'Durian', 33)
>>> result3
('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
result1: tuple[str, str, str] | tuple[str,str,int]
result2: tuple[str, str, str] | tuple[str,str,int]
result3: tuple[str, str, str] | 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
result1 = ...
result2 = ...
result3 = ...
# %% 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 `result1: tuple` with row from `DATA` at index -1
# 2. Define `result2: tuple` with row from `DATA` at index -3
# 3. Define `result3: tuple` with row from `DATA` at index -5
# 4. Use getitem, i.e.: `list[index]`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result1: tuple` z wierszem z `DATA` o indeksie -1
# 2. Zdefiniuj `result2: tuple` z wierszem z `DATA` o indeksie -3
# 3. Zdefiniuj `result3: tuple` z wierszem z `DATA` o indeksie -5
# 4. Użyj getitem, tj. `list[index]`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> result1
# ('Mallory', 'Melon', 15)
#
# >>> result2
# ('Dave', 'Durian', 33)
#
# >>> result3
# ('Bob', 'Blackthorn', 31)
# %% 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 tuple, \
'Variable `result1` has an invalid type; expected: `tuple`.'
>>> assert len(result1) == 3, \
'Variable `result1` has an invalid length; expected: `3`.'
>>> 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 tuple, \
'Variable `result2` has an invalid type; expected: `tuple`.'
>>> assert len(result2) == 3, \
'Variable `result2` has an invalid length; expected: `3`.'
>>> 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 tuple, \
'Variable `result3` has an invalid type; expected: `tuple`.'
>>> assert len(result3) == 3, \
'Variable `result3` has an invalid length; expected: `3`.'
>>> result1
('Mallory', 'Melon', 15)
>>> result2
('Dave', 'Durian', 33)
>>> result3
('Bob', 'Blackthorn', 31)
"""
# %% 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: tuple[str,str,int]
result2: tuple[str,str,int]
result3: 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
result1 = ...
result2 = ...
result3 = ...
# %% 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ść
# %% Expected
# >>> result
# [('firstname', 'lastname', 'age'),
# ('Alice', 'Apricot', 30),
# ('Mallory', 'Melon', 15)]
# %% Hints
# - `list.append()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python has an is invalid version; expected: `3.12` or newer.'
>>> from pprint import pprint
>>> assert 'result' in globals(), \
'Variable `result` is not defined; assign result of your program to it.'
>>> assert result is not Ellipsis, \
'Variable `result` has an invalid value; assign result of your program to it.'
>>> assert type(result) is list, \
'Variable `result` has an invalid type; expected: `list`.'
>>> assert len(result) == 3, \
'Variable `result` has an invalid length; expected: `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 -f -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', 'Blackthorn', 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ść
# %% Expected
# >>> header
# ('firstname', 'lastname', 'age')
#
# >>> rows
# [('Alice', 'Apricot', 30),
# ('Bob', 'Blackthorn', 31),
# ('Carol', 'Corn', 32),
# ('Dave', 'Durian', 33),
# ('Eve', 'Elderberry', 34),
# ('Mallory', 'Melon', 15)]
# %% Hints
# - `list.append()`
# %% 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`.'
>>> assert header not in rows, \
'Header should not be in `rows`'
>>> 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`.'
>>> content = open(__file__).read()
>>> assert 'DATA'+'[1:]' not in content, \
'Slice `list[start:stop:step]` was used; expected: use getitem `list[index]`.'
>>> assert 'DATA'+'[1:11]' not in content, \
'Slice `list[start:stop:step]` was used; expected: use getitem `list[index]`.'
>>> pprint(header)
('firstname', 'lastname', 'age')
>>> 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 = ...