PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
""" reduce() hack """
# Normally the reduce() function is able to apply a function to pairs of values in a list, resulting in a single value.
# But actually if we start out with an empty list and use the append() function, the result can be similar to map, or the number of elements can even increase in the result set!
from functools import reduce
def enrich(x, y):
"""Add a number to list, and if it is odd, also add its negative."""
x.append(y)
if y % 2:
x.append(-y)
return x
# print(enrich([], 2))
# print(enrich([2], 3))
nums = [i for i in range(7)]
print(nums)
# This is the trick!
enriched = reduce(enrich, nums, [])
print(enriched)
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run