Python

Important Statements

Single line Functions(Lambda)

The map() Function

Applies a given function to each item of an iterable (or multiple iterables) and returns an iterator of the results.

map(function, iterable, ...)

Example:

numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
# squared is [1, 4, 9, 16]

words = ["apple", "banana", "cherry"]
lengths = list(map(len, words))
# lengths is [5, 6, 6]

The filter() Function

Constructs an iterator from elements of an iterable for which a function returns true.

filter(function, iterable)

Example:

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# evens is [2, 4, 6]

words = ["apple", "banana", "cherry", "date"]
short_words = list(filter(lambda w: len(w) < 6, words))
# short_words is ['apple', 'date']

The sorted() Function