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. Technically, an iterable must implement the .__iter__()
special method which returns an iterator, or implement .__getitem__()
to support indexing.
Common built-in iterables include lists, tuples, strings, dictionaries, and sets.
Iterables form the backbone of Python’s for
loops and can be used in list comprehensions, generator expressions, and with the in
operator. Unlike iterators, iterables can be traversed multiple times and typically represent a sequence or collection of data that exists in memory.
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: The Pythonic Way (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)