Iterable
In Python, an iterable is an object that can return its elements one at a time, allowing you to loop over it using a for
loop or any other iteration tool. Common examples of iterables include lists, tuples, strings, dictionaries, and sets.
When you use a for
loop, Python implicitly calls the built-in iter()
function on the object, which returns an iterator. The iterator then yields each item from the iterable one at a time.
Iterables may implement the .__iter__()
magic method, which returns an iterator object. They can also implement the the .__getitem__()
method.
Python Iterable Example
Here’s an example that demonstrates how to iterate over a list, which is a common type of iterable:
>>> fruits = ["apple", "banana", "cherry"]
>>> for fruit in fruits:
... print(fruit)
...
apple
banana
cherry
In this example, the list fruits
is an iterable object, and the for
loop iterates over each element, printing it to the console.
Related Resources
Tutorial
Iterators and Iterables in Python: Run Efficient Iterations
In this tutorial, you'll learn what iterators and iterables are in Python. You'll learn how they differ and when to use them in your code. You'll also learn how to create your own iterators and iterables to make data processing more efficient.
For additional information on related topics, take a look at the following resources:
- Python "for" Loops (Definite Iteration) (Tutorial)
- How to Iterate Through a Dictionary in Python (Tutorial)
- Python's map(): Processing Iterables Without a Loop (Tutorial)
- Efficient Iterations With Python Iterators and Iterables (Course)
- Iterators and Iterables in Python: Run Efficient Iterations (Quiz)
- For Loops in Python (Definite Iteration) (Course)
- The Python for Loop (Quiz)
- Python Dictionary Iteration: Advanced Tips & Tricks (Course)
- Python Dictionary Iteration (Quiz)
- Python's map() Function: Transforming Iterables (Course)