Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is an iterable in Python

Understanding Iterables in Python

When you're starting out in the world of programming, especially with Python, you'll often come across the term "iterable." But what does it mean? In its simplest form, an iterable in Python is anything that you can loop over with a for loop. It's like a collection of items that you can go through one by one.

Imagine you have a box of crayons. You can take out each crayon one after the other to see its color. In Python, this box could be considered an iterable, and each crayon is an item you can iterate over.

The Basics of Iterables

In Python, iterables include lists, strings, tuples, dictionaries, and sets. Each of these has elements that can be accessed in a sequence, or one after another. Let's look at a simple example using a list:

colors = ['red', 'blue', 'green', 'yellow']
for color in colors:
    print(color)

In this example, colors is a list of color names, and it's also an iterable. When we use a for loop, we can print out each color in the list one by one.

Iterables and the for Loop

The for loop is the most common way to iterate over an iterable. The loop takes each item from the iterable, one at a time, and does something with it. Here's how you can use a for loop with a string, which is also an iterable:

word = "hello"
for letter in word:
    print(letter)

In this case, the string "hello" is the iterable, and each character in the string is printed on a separate line.

Understanding Iterators

Now, you might be wondering what actually happens behind the scenes when we use a for loop. This is where the concept of an "iterator" comes in. An iterator is like a conveyor belt for an iterable—it knows how to get the next item from the collection.

Every time you use a for loop, Python automatically creates an iterator from the iterable and starts fetching items from it. This is done using the iter() function. Here's how it looks in practice:

colors = ['red', 'blue', 'green', 'yellow']
colors_iterator = iter(colors)
print(next(colors_iterator)) # prints 'red'
print(next(colors_iterator)) # prints 'blue'

We used iter() to create an iterator for the list colors. Then, by calling next(), we got the next item from the iterator. Once an item is consumed by next(), it's gone from the iterator, just like when you take a crayon out of the box.

Iterables and Functions

Python has many built-in functions that work with iterables. For example, the len() function gives you the number of items in an iterable:

colors = ['red', 'blue', 'green', 'yellow']
print(len(colors)) # prints 4

Another useful function is sorted(), which returns a new list containing all items from the iterable in ascending order:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
print(sorted(numbers)) # prints [1, 1, 2, 3, 4, 5, 5, 6, 9]

Dictionaries Are Iterables Too

Dictionaries in Python are a bit special when it comes to iteration. When you iterate over a dictionary, you're actually iterating over its keys by default. Here's an example:

capitals = {'USA': 'Washington, D.C.', 'France': 'Paris', 'Italy': 'Rome'}
for country in capitals:
    print(country)

This will print the names of the countries, not the capitals. If you want to iterate over the values or the pairs of keys and values, you can use the .values() or .items() methods, respectively:

# To iterate over values
for capital in capitals.values():
    print(capital)

# To iterate over key-value pairs
for country, capital in capitals.items():
    print(country, capital)

Custom Iterables

What if you want to create your own iterable? In Python, this is possible by defining a class with __iter__() and __next__() methods. This might sound complex, but let's break it down with an example:

class Countdown:
    def __init__(self, start):
        self.current = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        else:
            self.current -= 1
            return self.current + 1

countdown = Countdown(3)
for number in countdown:
    print(number)

In this example, we created a Countdown class that can be iterated over. It counts down from the number provided to zero. The __iter__() method returns the iterator object itself, and the __next__() method returns the next value. When there are no more values, it raises a StopIteration exception, which tells the for loop to stop.

Conclusion: The Power of Iterables

Iterables are a fundamental concept in Python that provide a powerful and flexible way to work with collections of items. They are used in for loops, comprehensions, and many built-in functions, making them an indispensable part of the language.

As you continue your journey in programming, you'll find that understanding and using iterables effectively will open up a world of possibilities. They allow you to handle data with ease, whether you're dealing with a few items or millions. So, the next time you come across a list, a string, or any other collection in Python, remember that you're working with an iterable—a simple yet profound concept that's as versatile as it is essential.