The most important built-in methods
The map()
method
The map()
method takes a function and a list of numbers as parameters. It applies the given function to each item in the list and returns a new one with the results.
print(list(map(lambda x: x + 3, [1, 2, 3, 4])))
*This fuction doesn't have to be a lambda
.
We can also use map()
with input().split()
to read and convert the type of multiple input values at once.
n, m = map(int, input().split())
print("Sum:", n + m)
The filter()
method
The filter()
method takes a function and a list of numbers as parameters. It applies the given function to each item in the list and returns a new one with only those items for which the function returned True
.
print(list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4])))
The reduce()
method
The reduce()
method takes a function and a list of numbers as parameters. It applies a rolling computation to sequential pairs of values in the list, ultimately reducing (in this case - summing) them to a single value.
from functools import reduce
print(reduce(lambda x, y: x + y, [1, 2, 3, 4]))
The zip()
method
The zip()
method can be used to process multiple iterables (iterable objects) simultaneously (the first example) or to combine elements of two or more iterables into one object (the second example).
strings = ["a", "ab", "abc"]
counts = [len(n) for n in strings]
longest_string = None
max_count = 0
for string, count in zip(strings, counts):
if count > max_count:
longest_string = string
max_count = count
print(longest_string)
list1 = ["1", "2", "3", "4"]
list2 = ["a", "b", "c", "d"]
merged = list(zip(list1, list2))
print(merged)
The enumerate()
method
I have already mentioned this method in the lesson about data structures. It is very useful and preferred over range()
.
# Accessing the item and its index simultaneously while iterating a list (it works with all iterable data structures)
x = ["a", "b", "c", "d"]
for index, item in enumerate(x):
print(index, item)
x = enumerate(["a", "b", "c", "d", "e", "f"])
print(next(x)) # (0, "a")
print(next(x)) # (1, "b")
x = [["a", 1], ["b", 2], ["c", 3]]
for index, [name, number] in enumerate(x):
print(f"{index}: {number} belongs to {name}")