9.8. Built-in Generators

9.8.1. range()

  • optional start, inclusive, default: 0

  • required stop, exclusive,

  • optional step, default: 1

Listing 200. range() syntax
range([start], <stop>, [step])
Listing 201. range() definition
range(0,3)
# range(0,3)

list(range(0,3))
# [0, 1, 2]

tuple([0, 1, 2])
# (0, 1, 2)
Listing 202. range() examples
for number in range(4, 11, 2):
    print(number)

# 4
# 6
# 8
# 10

9.8.2. zip()

Listing 203. zip() syntax
zip(<sequence>, <sequence>, ...)
Listing 204. zip() definition
header = ['a', 'b', 'c']
data = [1, 2, 3]

zip(header, data)
# <zip object at 0x11cf54b90>

list(zip(header, data))
# [('a', 1), ('b', 2), ('c', 3)]

dict(zip(header, data))
# {'a': 1, 'b': 2, 'c': 3}

tuple(zip(header, data))
# (('a', 1), ('b', 2), ('c', 3))
Listing 205. zip() examples
header = ['a', 'b', 'c']
data = [1, 2, 3]
row = [77,88,99]

[(k,v,r) for k,v,r in zip(header, data, row)]
# [('a', 1, 77), ('b', 2, 88), ('c', 3, 99)]

9.8.3. map()

Listing 206. map() syntax
map(<callable>, <sequence>)
Listing 207. map() definition
data = [1, 2, 3]

list(map(float, data))
# [1.0, 2.0, 3.0]
Listing 208. map() examples
map(float, [1, 2, 3])
# <map object at 0x11d15a190>

list(map(float, [1, 2, 3]))
# [1.0, 2.0, 3.0]

tuple(map(float, [1, 2, 3]))
# (1.0, 2.0, 3.0)

9.8.4. filter()

Listing 209. filter() syntax
filter(<callable>, <sequence>)
Listing 210. filter() example
DATA = [
    {'name': 'Jan Twardowski', 'age': 21},
    {'name': 'Mark Watney', 'age': 25},
    {'name': 'Melissa Lewis', 'age': 18},
]

def is_adult(person):
    if person['age'] >= 21:
        return True
    else:
        return False


output = filter(is_adult, DATA)
print(list(output))
# [
#   {'name': 'Jan Twardowski', 'age': 21},
#   {'name': 'Mark Watney', 'age': 25},
# ]
Listing 211. filter() example
data = [1, 2, 3, 4, 5, 6]

def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

filter(is_even, data)
# <filter object at 0x11d182990>

list(filter(is_even, data))
# [2, 4, 6]

9.8.5. enumerate()

Listing 212. enumerate() syntax
enumerate(<sequence>)
Listing 213. enumerate() definition
header = ['a', 'b', 'c']

list(enumerate(header))
# [(0, 'a'), (1, 'b'), (2, 'c')]

dict(enumerate(header))
# {0: 'a', 1: 'b', 2: 'c'}
Listing 214. enumerate() example
header = ['a', 'b', 'c']
data = [1, 2, 3]
output = {}

for i, _ in enumerate(header):
    key = header[i]
    value = data[i]
    output[key] = value

print(output)
# {'a': 1, 'b': 2, 'c': 3}

9.8.6. all()

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
    if not iterable:
        return False

    for element in iterable:
        if not element:
            return False

    return True

9.8.7. any()

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    if not iterable:
        return False

    for element in iterable:
        if element:
            return True

    return False

9.8.8. Assignments

9.8.8.1. Built-in Generators

English
  1. Using generator expression to create output: List[int] with numbers from 1 to 33 which are divisible by 3

  2. Filter output to contain only odd numbers

  3. Cube all numbers in output

  4. Calculate arithmetic mean from output

Polish
  1. Używając wyrażenia generatorowego stwórz output: List[int] z liczbami z zakresu 1 do 33 podzielnymi przez 3

  2. Przefiltruj output aby zawierał tylko liczby nieparzyste

  3. Podnieś wszystkie liczby w output do sześcianu

  4. Oblicz średnią arytmetyczną z output

Hint
  • mean = sum(...) / len(...)

  • type cast to list() before calculating mean to expand generator