Python Iterables
tags: #python/intro
In Python, an iterator is an object that allows you to iterate over collections of data, such as:
- Lists
- Python Tuples
- Python Dictionaries
- Python Sets
Yes. A string is also an iterable objects. When iterating over a string, each character is treated as an individual element.
An iterable object can be homogenous or heterogenous.
- Homogenous: all elements of an iterable object are of the same data type (e.g., string sequence)
- Heterogenous: elements of an iterable object are of different data types.
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'