Date Tags python

zip

zip merges collections of data into pairs. For example:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
zip(a, b)

# Output: [(1, 5), (2, 6), (3, 7), (4, 8)]

zip also works when the containers are of unequal length:

a = [1, 2]
b = [5, 6, 7, 8]
zip(a, b)

# Output: [(1, 5), (2, 6)]

zip can also "unzip" its own output:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
z = zip(a, b)

a, b = zip(*z)

print(a)
print(b)
# Output: [1, 2, 3, 4]
# Output: [5, 6, 7, 8]

map

map applies a function to each item in an iterable container.

a = [1, 2, 3, 4]
map(lambda x: x + 1, a)

# Output: [2, 3, 4, 5]

In this case, we applied lambda function to the list a which adds 1 to every element of a.

A more complicated example using the function max:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = map(max, a, b)

# Output: [5, 6, ,7, 8]

filter

filter creates a list in which the elements are true according to a function.

a = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, a)
print(a)

# Output: [2, 4]

reduce

Given a list, reduce returns the result of a computation (calculated on sequential pairs of list values). The computation rolls through each sequential pair until it returns a result.

from functools import reduce
a = [1, 2, 3, 4, 5]
sum = reduce((lambda x, y: x + y), a)

# Output: 15


Comments

comments powered by Disqus