Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 7 of 13

Iterables

What makes an object iterable, the many iterables in Python (sequences, sets, dicts, files, ranges, generators), and the tools that accept any iterable: for, list(), sum(), zip() and enumerate().

Beginner 10 min read·Lesson 151 of 306 in Python Programming

Learning objectives

  • Recognise iterable objects
  • Use functions that accept any iterable
  • Test whether an object is iterable

Definition

An iterable is any object that can return its elements one at a time, so it can be used in a for loop. Technically, an iterable implements __iter__() (or __getitem__ with integer indexes) and iter(obj) returns an iterator over it.

Introduction

Lists, strings, tuples, dictionaries, sets, ranges, files and generators can all appear after for … in. They are all iterables — objects that know how to hand out their items one by one.

Why it matters

Because so many functions accept any iterable — sum, max, sorted, set, list, zip, enumerate — understanding iterables lets you combine Python's tools freely, and design your own functions to be equally flexible.

Detailed explanation

Sequences (list, tuple, str, range) are iterables with a defined order and indexing. Sets and dictionaries are iterables without indexing; iterating a dictionary yields its keys.

Some iterables are reusable (a list can be looped over many times); others are one-shot (generators, files after reading, iterators).

enumerate(iterable, start=0) yields (index, item) pairs; zip(a, b, ...) yields tuples combining items in parallel and stops at the shortest.

Functions written as def total(values): return sum(values) work with any iterable of numbers — write functions to accept iterables rather than only lists.

isinstance(obj, collections.abc.Iterable) checks for iterability; the most reliable test is simply trying iter(obj), which raises TypeError for non-iterables such as integers.

Syntax

Python
for item in iterable: ...
list(iterable), set(iterable), sorted(iterable), sum(iterable)
for i, item in enumerate(iterable, start=1): ...
for a, b in zip(first, second): ...
  • Iterables can be looped over.
  • Many built-ins accept any iterable.
  • Dicts iterate over keys.

Code examples

Many kinds of iterable

Python
for thing in [[1, 2], "hi", (3, 4), {"a": 1, "b": 2}, range(2)]:
print(type(thing).__name__, list(thing))
Output
list [1, 2]
str ['h', 'i']
tuple [3, 4]
dict ['a', 'b']
range [0, 1]

enumerate and zip

Python
names = ["Asha", "Ravi", "Meera"]
marks = [91, 74, 88]
for rank, (name, mark) in enumerate(zip(names, marks), start=1):
print(rank, name, mark)
Output
1 Asha 91
2 Ravi 74
3 Meera 88

More examples

Writing functions that accept any iterable

Python
from collections.abc import Iterable
def average(values):
total = count = 0
for v in values: # works for lists, tuples, sets, generators...
total += v
count += 1
return total / count if count else 0
print(average([1, 2, 3]), average((10, 20)), average({4, 4, 8}), average(x * 2 for x in range(4)))
for obj in [42, "text", [1], {"k": 1}]:
print(repr(obj), isinstance(obj, Iterable))
try:
iter(42)
except TypeError as e:
print(e)
Output
2.0 15.0 6.0 3.0
42 False
'text' True
[1] True
{'k': 1} True
'int' object is not iterable

Step-by-step explanation

  • average uses only a for loop, so any iterable of numbers works — including a set (duplicate 4 removed) and a generator.
  • Counting while iterating avoids len(), which generators don't support.
  • isinstance(..., Iterable) reports which objects can be looped over.
  • iter(42) fails with the familiar 'not iterable' TypeError.

Expected output

Running “Writing functions that accept any iterable” prints exactly:

TextOutput
2.0 15.0 6.0 3.0
42 False
'text' True
[1] True
{'k': 1} True
'int' object is not iterable

Practical applications

  • File objects iterate over lines: for line in open(path).
  • Database cursors and API pagers are iterables of rows or pages.

Best practices

  • Accept iterables in your functions, not just lists.
  • Use enumerate instead of range(len(...)).
  • Use zip to walk several sequences together.

Common mistakes

Iterating an integer

Avoid

for i in 5: ...

Prefer

for i in range(5): ...

An int isn't iterable; range(5) is.

Expecting values when iterating a dict

Avoid

for v in prices: total += v # v is a key

Prefer

for v in prices.values(): total += v

Iterating a dictionary yields keys; use values() or items().

Important notes

  • zip(strict=True) (Python 3.10+) raises an error if the iterables have different lengths.

Key takeaways

  • Iterables can be used in for loops and with list(), sum(), sorted() and friends.
  • Some are reusable, some one-shot.
  • iter(obj) raises TypeError for non-iterables.

Try it yourself

  1. 1
    Write longest(items) that works for any iterable of strings.
  2. 2
    Print a numbered list of three parallel lists using enumerate and zip.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Comprehensions and Advanced Iteration” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module