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)
returnsTrue
if every element ofiterable
evaluates to a true value. -
any(iterable)
returnsTrue
if at least one element ofiterable
evaluates to a true value. -
filter(test, iterable)
returns an iterator for the items initerable
that pass thetest
. -
len(iterable)
returns the number of elements initerable
. -
list(iterable)
returns a list of the elements initerable
in the same order. -
map(function, iterable)
returns an iterator. Each value returned by the iterator will be the result of applying thefunction
to the corresponding value of theiterable
. -
max(iterable)
returns the largest value initerable
. -
min(iterable)
returns the smallest value initerable
. -
set(iterable)
returns a set of the values initerable
. -
sorted(iterable)
returns a list of the elements initerable
in sorted order. -
sum(iterable)
returns the sum of the values initerable
. -
tuple(iterable)
returns a tuple of the elements initerable
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
returnsTrue
if the element is initerable
. -
element not in iterable
returnsTrue
if the element is not initerable
.
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 1400+ tech skills courses.