map() / filter() / sorted()
| Since: | Python 2(2000) |
|---|
Higher-order functions for transforming, filtering, and sorting iterables. Along with list comprehensions, they are central to data processing in Python.
Syntax
# Applies a function to each element of an iterable and returns the results. map(function, iterable, ...) # Returns only the elements for which the function returns True. filter(function, iterable) # Returns a new sorted list (the original iterable is not modified). sorted(iterable, key=None, reverse=False) # Returns the minimum value, maximum value, or sum of an iterable. min(iterable, key=None) max(iterable, key=None) sum(iterable, start=0)
Function List
| Function | Description |
|---|---|
| map(func, iterable) | Returns an iterator that applies a function to each element. Use list() or another conversion to get the results as a sequence. |
| filter(func, iterable) | Returns an iterator of elements for which the function returns True. Passing None as func removes all falsy values. |
| sorted(iterable, key, reverse) | Returns a new sorted list from the iterable. Use the key parameter to specify a custom sort criterion. |
| min(iterable, key) | Returns the smallest value in the iterable. A key function can be used for custom comparisons. |
| max(iterable, key) | Returns the largest value in the iterable. A key function can be used for custom comparisons. |
| sum(iterable, start=0) | Returns the sum of numeric values in the iterable. Use start to set an initial value. |
Sample Code
sample_map_filter_sorted.py
# Use map() to transform each element.
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# Convert a list of strings to integers.
str_nums = ["10", "20", "30"]
int_nums = list(map(int, str_nums))
print(int_nums) # [10, 20, 30]
# Use filter() to keep only elements that match a condition.
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
# Passing None removes all falsy values.
data = [1, 0, "hello", "", None, [], [1, 2]]
clean = list(filter(None, data))
print(clean) # [1, 'hello', [1, 2]]
# Use sorted() to create a new sorted list.
fighters = ["Vegeta", "Krillin", "Son Goku", "Bulma"]
sorted_fighters = sorted(fighters)
print(sorted_fighters) # Sorted in alphabetical order.
# Sort by string length using a key function.
sorted_by_len = sorted(fighters, key=len)
print(sorted_by_len) # Sorted from shortest to longest string.
# Sort a list of dictionaries by a specific key.
students = [
{"name": "Son Goku", "score": 92},
{"name": "Vegeta", "score": 85},
{"name": "Krillin", "score": 78},
]
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
print(by_score[0]["name"]) # Son Goku (highest score)
# Using min(), max(), and sum().
scores = [85, 92, 78, 95, 70]
print(min(scores)) # 70
print(max(scores)) # 95
print(sum(scores)) # 420
print(sum(scores) / len(scores)) # 84.0 (average)
# Use a key function to find the dictionary with the highest score.
best = max(students, key=lambda s: s["score"])
print(best["name"]) # Son Goku
python3 map_filter_sorted.py [2, 4, 6, 8, 10] [10, 20, 30] [2, 4] [1, 'hello', [1, 2]] ['Bulma', 'Krillin', 'Son Goku', 'Vegeta'] ['Bulma', 'Vegeta', 'Krillin', 'Son Goku'] Son Goku 70 95 420 84.0 Son Goku
Notes
Both map() and filter() return lazy iterators. If you need the results as a list, always wrap them with list(). Without the conversion, you will see an object representation like <map object at 0x...> instead of the actual values.
In modern Python, list comprehensions are generally preferred over map() and filter() for readability. For example, list(map(lambda x: x*2, nums)) can be written as [x*2 for x in nums]. That said, map() is more concise when passing an existing function such as int or str.
Unlike the sort() method on lists, sorted() does not modify the original object — it always returns a new list. It also works with any iterable, including strings, tuples, and dictionary keys.
If you find any errors or copyright issues, please contact us.