Python offers a series of built-in functions and methods that facilitate the manipulation and processing of lists, tuples, and other iterables
Method | Description |
---|---|
map() | Applies a function to each element of an iterable |
filter() | Filters elements from an iterable based on a condition |
any() | Returns True if at least one element of the iterable is true |
all() | Returns True if all elements of the iterable are true |
sorted() | Returns a new sorted list from the elements of an iterable |
sum() | Calculates the sum of the elements of an iterable |
enumerate() | Adds an index to each element of an iterable |
reduce() | Reduces a sequence of elements to a single value by applying a cumulative function |
zip() | Combines elements from multiple iterables into tuples |
Functions on Iterables
Function map()
The map()
function in Python is used to apply a function to each element of a sequence and return an iterable with the results.
# Basic usage of map():
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squares = map(square, numbers)
print(list(squares)) # [1, 4, 9, 16, 25]
In this example,
map(square, numbers)
applies thesquare()
function to each element of the listnumbers
,- Returns a map object that contains the squares of the numbers.
Often, we will use the map()
function with a lambda function to make the code more concise:
# Using map() with a lambda function:
numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x ** 2, numbers)
print(list(squares)) # [1, 4, 9, 16, 25]
Function filter()
The filter()
function in Python is used to filter elements from a sequence based on a condition defined by a function.
# Basic usage of filter():
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = filter(is_even, numbers)
In this example,
filter(is_even, numbers)
filters the numbers from the listnumbers
- Returns a filter object that contains only the even numbers
Just like with map()
, a lambda function can also be used with filter()
:
# Basic usage of filter():
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = filter(is_even, numbers)
print(list(evens)) # Output: [2, 4, 6, 8, 10]
Functions any() and all()
The any()
and all()
functions in Python are boolean functions that return True
based on the values of an iterable
any()
if at least one element isTrue
all()
if all elements areTrue
(any()
) or all elements (all()
) of an iterable are true, respectively.
# Using any() and all():
values = [True, False, True, False, True]
is_any_true = any(values) # True
are_all_true = all(values) # False
These functions are useful for checking conditions in iterables (like lists or generators).
They are often used alongside map
to apply a function to the values of an iterable. For example, like this,
values = [1, 2, 3, 4, 5]
is_any_greater_than_ten = any(map(lambda x: x > 10, values)) # False
Function sorted()
The sorted()
function in Python returns a new sorted list from the elements of the specified iterable.
# Basic usage of sorted():
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
In this example, sorted(numbers)
will sort the list numbers
in ascending order and assign the result to sorted_numbers
.
Optionally, we can specify,
- A
key
function to customize the sorting - A
reverse
argument to invert the order
# Using sorted() with key and reverse:
words = ["python", "java", "c++", "ruby", "javascript"]
sorted_words = sorted(words, key=len, reverse=True)
print(sorted_words) # ['javascript', 'python', 'java', 'c++', 'ruby']
Here, sorted(words, key=len, reverse=True)
sorts the list words
by the length of the strings in descending order.
Function sum()
The sum()
function in Python returns the sum of the elements of the specified iterable, optionally starting from a specified initial value (default is 0).
# Basic usage of sum():
numbers = [1, 2, 3, 4, 5]
total_sum = sum(numbers) # 15
This example sums all the numbers in the list numbers
.
Function enumerate()
The enumerate()
function in Python returns an enumerated object that produces tuples with a counter and an element from the specified iterable, optionally starting from a specified index (default is 0).
# Basic usage of enumerate():
teams = ["Real Madrid", "Barcelona", "Atlético de Madrid"]
enumerated_teams = list(enumerate(teams, start=1))
print(enumerated_teams) # [(1, 'Real Madrid'), (2, 'Barcelona'), (3, 'Atlético de Madrid')]
In this example,
enumerate(teams, start=1)
enumerates the football teams starting from 1- Generates a list of tuples
(index, team)
.
Function reduce()
The reduce()
function in Python is used to reduce a sequence of elements to a single value by repeatedly applying a two-argument function to the elements of the sequence.
# Basic usage of reduce():
from functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
total_sum = reduce(add, numbers)
print(total_sum) # Output: 15
In this example,
reduce(add, numbers)
applies theadd()
function cumulatively to the elements of the listnumbers
- Results in the total sum of all numbers.
Since Python 3, the reduce()
function has been moved to the functools
module, so it must be imported from there.
Function zip()
The zip()
function in Python combines elements from multiple iterables into tuples until the shortest iterable is exhausted.
# Basic usage of zip():
names = ["Luis", "María", "Pedro"]
ages = [30, 25, 35, 40]
print(persons) # [("Luis", 30), ("María", 25), ("Pedro", 35)]
In this example, zip(names, ages)
combines the lists names
and ages
into a list of tuples (name, age)
.
In this case, it returns a collection of 3 tuples, because names only has 3 values. Each tuple combines a value from the names
iterable and the ages
iterable.