Iterables

Carson West

For Loops

Iterables

An iterable is an object that can be iterated upon, meaning you can traverse through its elements one at a time. This is done using a for loop or functions like next() with an iterator. Key characteristics:

Examples:

# Example with a list (iterable)
my_list = [10, 20, 30]]
for item in my_list:  # my_list implicitly creates an iterator
    print(item)

# Example with a generator (iterable)
def my_generator(n):
    for i in range(n):
        yield i

for i in my_generator(5): #my_generator implicitly creates an iterator
    print(i)

# Manually creating and using an iterator
my_list = [10, 20, 30]]
my_iterator = iter(my_list)  # Get the iterator
print(next(my_iterator)) # 10
print(next(my_iterator)) # 20
print(next(my_iterator)) # 30

# Attempting to access beyond the end raises StopIteration
# print(next(my_iterator))  # StopIteration exception

Key Differences from Iterators: Iterables produce iterators; iterators are the objects that perform the actual iteration. An iterable can be used to create many iterators.

Related Notes: