Iterable Functions

There are many built-in functions in Python for processing iterables (such as list).

Some of them are:

  • map
  • filter
  • all
  • any
  • reduce

map

Returns an object of map class which elements are modified according to the function.

The map class can be converted to some other collection with functions like:

  • list() - to convert to list
  • set() - to convert to a set, and so on.

Output:

filter

Returns an object of filter class which can be converted to other collection via list(), set() and other functions.

Allows filtering specific elements.

if the function returns true - the element will be present in the returned collection.

If the function returns false - it will not be present.

For example we can filter the list to return only the even numbers:

Output:

all

Returns a boolean. True - if all elements meet certain condition and False - if one or more elements don't meet the condition.

Let's look at the following example:

Output:

any

Returns a boolean. True - if at least one of the elements meets certain condition and False - if all of the elements don't meet the condition.

Let's look at the following example:

Output:

reduce

The reduce function is part of the functools module and is used to accumulate a single value from the list.

It receives three arguments:

  • A function which describes how to accumulate the end value through the iterations.
  • iterable collection such as list
  • initial value

Let's look at the following example:

Output:

The following calculations are made until the end value - 20 is reached.

  • The initial value starts with 5 (the third argument) - Total Value = 5.

  • Total Value = Total Value + 3 + 1
  • Total Value = 5 + 3 + 1 = 9

  • Total Value = Total Value + 7 + 1
  • Total Value = 9 + 7 + 1 = 17

  • Total Value = Total Value + 2 + 1
  • Total Value = 17 + 2 + 1 = 20