Definition: In Python, an iterable is any object that can be traversed element by element. Technically, an iterable is an object capable of returning an iterator when the built-in function iter() is applied to it. This allows it to be used in for loops, list comprehensions, and many built-in functions that consume sequences.
Iterable vs Iterator
- Iterable: an object capable of providing an iterator (e.g.
list,tuple,dict,set,str). - Iterator: an object that knows how to return elements one by one using
next()until the sequence is exhausted (raisingStopIteration).
colors = {"red", "blue", "green"} # a set is iterable
it = iter(colors) # obtain an iterator (set_iterator)
print(next(it)) # returns one element from the set
Sets (set) as Iterables
Python set objects are iterable: they can be traversed with a for loop and converted into other collections. They are unordered and do not allow duplicates.
A = {"red", "blue", "green"}
for color in A:
print(color) # order is not guaranteed
lst = list(A) # conversion possible, but order may vary
Consequences of Unordered Nature
- You cannot index a
set(e.g.A[0]is invalid). - If order is required, convert to a
listand sort it:sorted(A).
Examples of Iteration
# List
nums = [2, 4, 6]
for n in nums:
print(n)
# Dictionary (iterates over keys)
d = {"a": 1, "b": 2}
for k in d: # equivalent to: for k in d.keys():
print(k, d[k])
# Set
s = {1, 2, 3}
for x in s:
print(x)
Useful Functions and Patterns with Iterables
len(iterable),sum(numbers),max(iterable),min(iterable)list(iterable),tuple(iterable),set(iterable)- Comprehensions:
[f(x) for x in iterable],{f(x) for x in iterable} any(it)andall(it)for efficient logical checks
Common Errors and Best Practices
- Set indexing: not allowed; use
sorted(set_)if you need positions. - Iterator exhaustion: once an iterator is consumed, it cannot be reused; create a new one with
iter(iterable)if needed. - Large data: prefer generators for memory efficiency when working with big sequences.
See Also
- Iterator (Python): object returned by
iter()and consumed bynext(). - Set (
set): iterable, unordered collection without duplicates. - Comprehensions: concise syntax to build new collections from iterables.
- Generators and
yield: create custom iterators that produce values on demand.