Python Iterables

tags: #python/intro

In Python, an iterator is an object that allows you to iterate over collections of data, such as:


Built-in Functions that act on Iterables

Constructing a list, tuple, dictionary, or set

To construct a list, tuple, dictionary, or set, respectively, from the elements of an iterable:

>>> list("I am a cow")
['I', ' ', 'a', 'm', ' ', 'a', ' ', 'c', 'o', 'w']

sum

Returns the aggregated sum of the elements of an iterable that are numeric in value:

>>> sum([1, 2, 3], start=0) 
6

#start is an optional parameter that specifies the initial value of the sum. Default is 0.

sorted

The sorted function in Python is used to return a new sorted list from the elements of any iterable (e.g., a list, tuple, or string). The basic syntax is as follows:

sorted(iterable, key=None, reverse=False)

# example
>>> sorted("gheliabciou")
['a', 'b', 'c', 'e', 'g', 'h', 'i', 'i', 'l', 'o', 'u']

any

The any function in Python is a built-in function that returns True if at least one element of an iterable is true, and False otherwise. The basic syntax is as follows:

any(iterable)

Example using a list of boolean values:

values = [False, True, False, True]
result = any(values)
print(result)  # Output: True

In this example, the any function returns True because at least one element in the list (True) is true.

The any function can be useful in various situations, such as checking if any element in a list meets a specific condition. For instance, checking if any number in a list is even:

numbers = [1, 3, 5, 8, 9]
result = any(num % 2 == 0 for num in numbers)
print(result)  # Output: True

min and max

Returns the smallest and largest value in an iterable object respectively:

>>> max((5, 8, 9, 0))
9

>>> min("hello")
'e'
Powered by Forestry.md