Advanced Collections and Built-in Functions¶
By the end of this lesson you'll be able to:
- Use
enumerate()for indexed loops andzip()to combine iterables - Write flexible functions with
*argsand**kwargs - Build dictionaries from two lists using
zip() - Use
max(),min(),sum(),sorted(),reversed(),map(), andfilter()with confidence
Python's built-in functions are a powerful toolkit. This chapter gathers the most useful ones so you can write shorter, cleaner code that does more.
Welcome to Chapter 22!
Python's built-in toolkit is like a Swiss Army knife — there's a tool for almost everything!
Today we're learning the ones you'll reach for most often.
Let's code it together!
enumerate() — Loop with an Index¶
enumerate(iterable) wraps a list (or any sequence) and gives you both the index and the item on each loop iteration.
Without enumerate(), you'd need a separate counter variable.
1 2 3 4 5 6 7 8 | |
Both produce the same output. enumerate() starts at 0 by default; use enumerate(fruits, 1) to start at 1.
zip() — Combine Iterables in Parallel¶
zip(a, b) pairs up items from two (or more) iterables step by step.
It stops when the shortest iterable runs out.
1 2 3 4 5 | |
What Do You Think Will Happen?
The code below zips two lists of different lengths.
How many pairs do you think zip() will produce?
Make your guess — then run it!
Were you right? zip() stops at 3 pairs because numbers runs out first.
Dictionary from Two Lists with zip()¶
Combine zip() with dict() to build a dictionary from two parallel lists — one of keys, one of values:
1 2 3 4 5 | |
*args — Variable Number of Positional Arguments¶
Sometimes you want a function that can accept any number of arguments.
*args collects all extra positional arguments into a tuple.
1 2 3 4 5 6 | |
**kwargs — Variable Number of Keyword Arguments¶
**kwargs collects extra keyword arguments into a dictionary.
1 2 3 4 5 | |
Aggregating Functions: max(), min(), sum()¶
These three built-ins work on any iterable of numbers (or comparables for max/min):
1 2 3 4 5 6 | |
sorted() and reversed()¶
sorted(iterable) returns a new sorted list without modifying the original.
reversed(iterable) returns an iterator that goes through items in reverse order.
| Function | Modifies original? | Returns |
|---|---|---|
list.sort() |
Yes | None |
sorted(list) |
No | New sorted list |
list.reverse() |
Yes | None |
reversed(list) |
No | Iterator |
1 2 3 | |
isinstance() — Type Checking¶
isinstance(value, type) returns True if the value is the given type (or a subtype).
It's safer than using type(x) == int because it handles inheritance.
1 2 3 4 5 | |
map() and filter()¶
map(func, iterable) applies a function to every item and returns the results.
filter(func, iterable) keeps only items where the function returns True.
Both return iterators — wrap them in list() to see the results:
1 2 3 4 5 6 7 | |
A lambda is a tiny anonymous function written on one line: lambda x: x * 2 means "take x, return x times 2."
Collection Constructors¶
You can convert between collection types using list(), tuple(), set(), and dict():
1 2 3 | |
Learning Check¶
Your Turn — Use enumerate and zip Together
The code below prints player names and their scores, but the output looks messy.
Fix it to use zip() to pair names with scores and enumerate() starting at 1 to number the entries.
Each line should look like: 1. Alice: 95
Experiments¶
Try these changes. Predict what will happen first, then run it to check!
-
Use
enumerate(["Mon","Tue","Wed","Thu","Fri"], 1)to print a numbered weekday list. You'll know it worked when you see1. Mon,2. Tue, etc. -
Write a function
my_max(*args)that returns the largest argument without using the built-inmax(). You'll know it worked whenmy_max(3, 9, 1, 7)returns9. -
Use
filter()to keep only strings longer than 4 characters from["cat","elephant","dog","hippo"]. You'll know it worked when you see["elephant","hippo"]. -
Use
sorted(words, key=len)to sort a list of words by their length (shortest first). You'll know it worked when short words appear before long ones. -
Use
dict(zip(range(1, 6), ["one","two","three","four","five"]))to build a number-to-word dictionary. You'll know it worked whend[3]prints"three".
Built-in Function Master!
You've leveled up with enumerate, zip, args, kwargs, map, filter, and more!
These tools make Python code shorter, more readable, and more powerful.
Professional programmers use every single one of them regularly. Great work!