9.1. Comprehension About

9.1.1. Recap

>>> result = []
>>>
>>> for x in range(0,5):
...     result.append(x)
>>>
>>> print(result)
[0, 1, 2, 3, 4]

9.1.2. Syntax

>>> 
... result = [<RETURN> for <VARIABLE> in <ITERABLE>]

9.1.3. Example

>>> result = [x for x in range(0,5)]
>>>
>>> print(result)
[0, 1, 2, 3, 4]

9.1.4. Rationale

  • Loop leaks out values

>>> result = []
>>>
>>> for x in range(0,5):
...     result.append(x)
>>>
>>> print(result)
[0, 1, 2, 3, 4]
>>>
>>> x
4
>>> result = [x for x in range(0,5)]
>>>
>>> print(result)
[0, 1, 2, 3, 4]
>>>
>>> x  
Traceback (most recent call last):
NameError: name 'x' is not defined

9.1.5. Syntax

Short syntax:

>>> [x for x in range(0,5)]
[0, 1, 2, 3, 4]

Long syntax:

>>> list(x for x in range(0,5))
[0, 1, 2, 3, 4]

9.1.6. Microbenchmark

>>> 
... %%timeit -r 1000 -n 1000
... result = []
... for x in range(0,5):
...     result.append(x)
...
457 ns ± 69.4 ns per loop (mean ± std. dev. of 1000 runs, 1000 loops each)
>>> 
... %%timeit -r 1000 -n 1000
... result = [x for x in range(0,5)]
...
411 ns ± 76.6 ns per loop (mean ± std. dev. of 1000 runs, 1000 loops each)

9.1.7. Good Practices

  • Use shorter variable names

  • x is common name

9.1.8. Assignments

Code 9.1. Solution
"""
* Assignment: Comprehension About Create
* Required: yes
* Complexity: easy
* Lines of code: 1 lines
* Time: 3 min

English:
    1. Use list comprehension
    2. Generate `result: list[int]` of numbers from 5 to 20 (without 20)
    3. Run doctests - all must succeed

Polish:
    1. Użyj rozwinięcia listowego
    2. Wygeneruj `result: list[int]` liczb z przedziału 5 do 20 (bez 20)
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `range()`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> assert type(result) is list, \
    'Result should be a list'

    >>> assert all(type(x) is int for x in result), \
    'Result should be a list of int'

    >>> result
    [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""

# list[int]: numbers from 5 to 20 (without 20)
result = ...