Skip to content

Module 6 · Loops and Iteration — topic 12 of 12

Iteration basics

What makes something iterable, how for works behind the scenes with iterators, and the built-in functions that consume iterables: sum, min, max, sorted, reversed, any, all, enumerate and zip.

Beginner 12 min read·Lesson 81 of 306 in Python Programming

Learning objectives

  • Explain what an iterable is
  • Use built-in functions that work on any iterable
  • Choose between a loop and a built-in function

Definition

What makes something iterable, how for works behind the scenes with iterators, and the built-in functions that consume iterables: sum, min, max, sorted, reversed, any, all, enumerate and zip.

Introduction

Anything you can loop over with for is called an iterable: lists, tuples, strings, sets, dictionaries, ranges and files are all iterables. Python provides many built-in functions that accept any iterable, which often replaces a hand-written loop with a single call.

Why it matters

Knowing these built-ins makes code shorter and less error-prone. sum(prices) can’t forget to initialise a total, and max(scores) can’t mishandle the first item. It also prepares you for comprehensions and generators in Module 10.

Detailed explanation

Behind the scenes, for asks the iterable for an iterator with iter() and repeatedly calls next() on it until it is exhausted. Module 10 explores this in detail.

sum(), min() and max() work on any iterable of comparable values. min and max accept key= to choose what to compare, such as key=len.

sorted(iterable) returns a new sorted list and leaves the original unchanged; list.sort() sorts a list in place and returns None.

reversed(sequence) gives the items in reverse order without copying them.

any() and all() test conditions across items.

enumerate() and zip() produce pairs, and list(), tuple() and set() collect an iterable into a container.

Use a loop when each item needs several steps or side effects; use a built-in when the operation is a single well-known reduction.

Syntax

Python
sum(values)
max(items, key=len)
sorted(items, reverse=True)
any(conditions)
all(conditions)
  • These accept any iterable.
  • key= tells min, max and sorted what to compare.
  • sorted returns a new list.

Code examples

Built-ins replace loops

Python
marks = [72, 45, 88, 39, 91]
print(sum(marks), min(marks), max(marks))
print(sorted(marks))
print(list(reversed(marks)))
Output
335 39 91
[39, 45, 72, 88, 91]
[91, 39, 88, 45, 72]

Many kinds of iterable

Python
print(max("python"))
print(sorted({3, 1, 2}))
print(sum(range(1, 101)))
print(list({"a": 1, "b": 2}))
Output
y
[1, 2, 3]
5050
['a', 'b']

More examples

Analysing a class with built-ins

Python
students = [("Asha", 82), ("Ben", 67), ("Chen", 91), ("Dev", 58)]
marks = [m for _, m in students]
print("Average:", sum(marks) / len(marks))
top = max(students, key=lambda s: s[1])
print("Top:", top[0])
print("All passed:", all(m >= 40 for m in marks))
print("Any above 90:", any(m > 90 for m in marks))
ranking = sorted(students, key=lambda s: s[1], reverse=True)
print([name for name, _ in ranking])
longest = max((name for name, _ in students), key=len)
print("Longest name:", longest)
Output
Average: 74.5
Top: Chen
All passed: True
Any above 90: True
['Chen', 'Asha', 'Ben', 'Dev']
Longest name: Asha

Step-by-step explanation

  • The comprehension collects just the marks from each (name, mark) pair.
  • max with key compares students by their mark and returns the whole pair.
  • all and any test a condition across every mark.
  • sorted with key and reverse=True ranks the students without changing the original list.
  • max(..., key=len) finds the longest name; Asha and Chen tie at four letters and the first one wins.

Expected output

Running “Analysing a class with built-ins” prints exactly:

TextOutput
Average: 74.5
Top: Chen
All passed: True
Any above 90: True
['Chen', 'Asha', 'Ben', 'Dev']
Longest name: Asha

Practical applications

  • Dashboards compute totals and maximums with sum and max.
  • Leaderboards sort players by score with sorted(..., key=...).
  • Validation code checks every field with all().

Best practices

  • Reach for sum, min, max, sorted, any and all before writing a loop.
  • Use key= instead of sorting manually.
  • Use sorted() when the original order must be kept.

Common mistakes

Assigning the result of list.sort()

Avoid

ordered = marks.sort()

Prefer

ordered = sorted(marks)

list.sort() sorts in place and returns None.

Calling max on an empty list

Avoid

max([])

Prefer

max(values, default=0)

max of an empty iterable raises ValueError unless a default is given.

Key takeaways

  • Iterables are anything you can loop over.
  • Built-ins such as sum, max, sorted, any and all accept any iterable.
  • sorted() returns a new list; list.sort() changes the list and returns None.

Try it yourself

  1. 1
    Find the shortest and longest words in a sentence using min and max with key=len.
  2. 2
    Check whether all characters in a PIN string are digits using all().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic