8.8. Function Generators

8.8.1. Range

  • optional start, inclusive, default: 0

  • required stop, exclusive,

  • optional step, default: 1

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

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

tuple(range(0,3))
# (0, 1, 2)

set(range(0,3))
# {0, 1, 2}

frozenset(range(0,3))
# frozenset({0, 1, 2})
list(range(4, 11, 2))
# [4, 6, 8, 10]
header = ['a', 'b', 'c']
data = [1, 2, 3]
result = {}

for i in range(len(header)):
    key = header[i]
    value = data[i]
    result[key] = value

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

8.8.2. Zip

Listing 8.39. zip() syntax
zip(<sequence>, <sequence>, ...)
Listing 8.40. 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)]

tuple(zip(header, data))
# (('a', 1), ('b', 2), ('c', 3))

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

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

dict(zip(header, data))
# {'a': 1, 'b': 2, 'c': 3}
Listing 8.41. zip() adjust to shortest sequence
header = ['a', 'b', 'c']
data = [1, 2, 3, 4, 5, 6]

result = zip(header, data)

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

result = [(h,d,r) for h,d,r in zip(header, data, row)]

print(result)
# [('a', 1, 77), ('b', 2, 88), ('c', 3, 99)]

8.8.3. Enumerate

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

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

dict(enumerate(header))
# {0: 'a', 1: 'b', 2: 'c'}

dict((v,k) for k,v in enumerate(data))
# {'a': 0, 'b': 1, 'c': 2}

{v:k for k,v in enumerate(data, start=5)}
# {'a': 5, 'b': 6, 'c': 7}
Listing 8.45. enumerate() example
header = ['a', 'b', 'c']
data = [1, 2, 3]
result = {}

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

print(result)
# {'a': 1, 'b': 2, 'c': 3}
header = ['a', 'b', 'c']
data = [1, 2, 3]
result = {}

for i, header in enumerate(header):
    result[header] = data[i]

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

8.8.4. Map

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

map(float, data)
# <map object at 0x11d15a190>

list(map(float, data))
# [1.0, 2.0, 3.0]

tuple(map(float, data))
# (1.0, 2.0, 3.0)

set(map(float, data))
# {1.0, 2.0, 3.0}

frozenset(map(float, data))
# frozenset({1.0, 2.0, 3.0})
Listing 8.48. map() examples
def square(x):
    return x ** 2

data = [1, 2, 3]

result = map(square, data)
list(result)
# [1, 4, 9]

8.8.5. Filter

Listing 8.49. filter() syntax
filter(<callable>, <sequence>)
data = [True, False, True]

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

result = filter(bool, data)
list(result)
# [True, True]
Listing 8.50. filter() example
def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

data = [1, 2, 3, 4, 5, 6]

result = filter(is_even, data)
list(result)
# [2, 4, 6]
def is_even(x):
    return x % 2 == 0

data = [1, 2, 3, 4, 5, 6]

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

8.8.6. Functools

from functools import *

reduce(callable, iterable[, initializer])

8.8.7. Itertools

from itertools import *

count(start=0, step=1)
cycle(iterable)
repeat(object[, times])
accumulate(iterable[, func, *, initial=None])
chain(*iterables)
compress(data, selectors)
islice(iterable, start, stop[, step])
starmap(function, iterable)
product(*iterables, repeat=1)
permutations(iterable, r=None)
combinations(iterable, r)
combinations_with_replacement(iterable, r)
groupby(iterable, key=None)

8.8.8. Examples

data = [1, 2, 3, 4]

def increment(x):
    return x + 1

result = map(increment, data)
list(result)
# [2, 3, 4, 5]
PL = {'ą': 'a', 'ć': 'c', 'ę': 'e',
      'ł': 'l', 'ń': 'n', 'ó': 'o',
      'ś': 's', 'ż': 'z', 'ź': 'z'}

text = 'zażółć gęślą jaźń'

def translate(letter):
    return PL.get(letter, letter)

result = map(translate, text)
''.join(result)
# 'zazolc gesla jazn'
Listing 8.51. filter() example
def adult(person):
    return person['age'] >= 21:

people = [
    {'age': 21, 'name': 'Jan Twardowski'},
    {'age': 25, 'name': 'Mark Watney'},
    {'age': 18, 'name': 'Melissa Lewis'}]

result = filter(adult, people)
list(result)
# [{'age': 21, 'name': 'Jan Twardowski'},
#  {'age': 25, 'name': 'Mark Watney'}]
Listing 8.52. filter() example
def astronaut(person):
    return person['is_astronaut']

people = [
    {'is_astronaut': False, 'name': 'Jan Twardowski'},
    {'is_astronaut': True, 'name': 'Mark Watney'},
    {'is_astronaut': True, 'name': 'Melissa Lewis'}]

result = filter(astronaut, people)
list(result)
# [{'is_astronaut': True, 'name': 'Mark Watney'},
#  {'is_astronaut': True, 'name': 'Melissa Lewis'}]
astronauts = ['Mark Watney', 'Melissa Lewis']

people = ['Jan Twardowski', 'Mark Watney',
          'Melissa Lewis', 'Jimenez']

def is_astronaut(person):
    return person in astronauts

result = filter(is_astronaut, people)
list(result)
# ['Mark Watney', 'Melissa Lewis']

8.8.9. Assignments

8.8.9.1. Function Generator Chain

  • Assignment name: Function Generator Chain

  • Last update: 2020-10-01

  • Complexity level: easy

  • Lines of code to write: 10 lines

  • Estimated time of completion: 13 min

  • Solution: solution/function_generators_chain.py

English
  1. Use generator expression to create numbers

  2. In generator use range() to get numbers from 1 to 33 (inclusive) divisible by 3

  3. Use filter() to get odd numbers from numbers

  4. Use map() to cube all numbers in numbers

  5. Create result: float with arithmetic mean of numbers

  6. Compare result with "Output" section (see below)

Polish
  1. Użyj wyrażenia generatorowego do stworzenia numbers

  2. W generatorze użyj range() aby otrzymać liczby od 1 do 33 (włącznie) podzielne przez 3

  3. Użyj filter() aby otrzymać liczby nieparzyste z numbers

  4. Użyj map() aby podnieść wszystkie liczby w numbers do sześcianu

  5. Stwórz result: float ze średnią arytmetyczną z numbers

  6. Porównaj wyniki z sekcją "Output" (patrz poniżej)

Output
>>> result
11502.0
Hints
  • type cast to list() before calculating mean to expand generator

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