Functions on Iterables

Learn about the different functions on iterables available in Python.

We'll cover the following

Introduction to functions on iterables

Here are some functions that take iterable objects (lists, sets, tuples, strings, dictionaries, ranges, files, and possibly others).

  • all(iterable) returns True if every element of iterable evaluates to a true value.

  • any(iterable) returns True if at least one element of iterable evaluates to a true value.

  • filter(test, iterable) returns an iterator for the items in iterable that pass the test.

  • len(iterable) returns the number of elements in iterable.

  • list(iterable) returns a list of the elements in iterable in the same order.

  • map(function, iterable) returns an iterator. Each value returned by the iterator will be the result of applying the function to the corresponding value of the iterable.

  • max(iterable) returns the largest value in iterable.

  • min(iterable) returns the smallest value in iterable.

  • set(iterable) returns a set of the values in iterable.

  • sorted(iterable) returns a list of the elements in iterable in sorted order.

  • sum(iterable) returns the sum of the values in iterable.

  • tuple(iterable) returns a tuple of the elements in iterable in the same order.

  • zip(iterable1, ...,iterableN) returns an iterator of N-tuples, where the first tuple contains the first value in each iterable, the second tuple contains the second value in each iterable, and so on. Iteration stops when any one of the iterables runs out of values.

  • element in iterable returns True if the element is in iterable.

  • element not in iterable returns True if the element is not in iterable.

In general, functions that take an iterable object can also take an iterator or a generator.

Some of the functions above have to examine every element of the iterable (max, for example). Others, like any, may or may not examine every element. Take care not to call such a function with an iterator or generator that produces an infinite number of values.

Get hands-on with 1200+ tech skills courses.