Reading history

Python Built-in Functions: enumerate, zip, sorted and More

5 min read 0 views

Master everyday Python built-in functions: enumerate, zip with strict, sorted, min and max with key, any, all, sum, map, filter, divmod and round.

Python ships with about 70 built-in functions that are always available without an import. A handful of them, used well, replace many lines of loop code: enumerate and zip for looping, sorted, min and max with a key, any and all for checks, and map and filter for transforming data. This lesson shows the ones you will use every day, with the details that often trip people up.

In this lesson you will learn

  • enumerate for an index and a value together
  • zip for looping over several sequences, and its strict option
  • sorted, min and max with a key function
  • sum, any and all with generator expressions
  • map, filter, divmod, round and other helpers

You should know for loops, lists and lambda functions.

Looping Helpers: enumerate, zip, reversed and range

students = ["Nusrat", "Arif", "Tania", "Mitu"]
cgpas = [3.82, 3.41, 3.95, 3.67]

# enumerate: index and value together (start=1 for human numbering)
for rank, name in enumerate(students, start=1):
    print(rank, name)

# zip: walk several sequences in parallel
for name, g in zip(students, cgpas):
    print(f"{name:<7}{g}")
print(dict(zip(students, cgpas)))

# zip stops at the shortest input; strict=True makes a mismatch an error
print(list(zip([1, 2, 3], "ab")))
try:
    list(zip([1, 2, 3], "ab", strict=True))
except ValueError as e:
    print("ValueError:", e)

# reversed and range
print(list(reversed(students)), list(range(10, 0, -3)))

Output

1 Nusrat
2 Arif
3 Tania
4 Mitu
Nusrat 3.82
Arif   3.41
Tania  3.95
Mitu   3.67
{'Nusrat': 3.82, 'Arif': 3.41, 'Tania': 3.95, 'Mitu': 3.67}
[(1, 'a'), (2, 'b')]
ValueError: zip() argument 2 is shorter than argument 1
['Mitu', 'Tania', 'Arif', 'Nusrat'] [10, 7, 4, 1]
  • enumerate(items, start=1) gives pairs of (position, item). It replaces the clumsy for i in range(len(items)) pattern.
  • zip pairs up items from several sequences: the first name with the first CGPA, and so on. dict(zip(keys, values)) is a quick way to build a dictionary.
  • By default zip stops silently at the shortest input, so 3 was dropped. Adding strict=True (Python 3.10+) raises an error instead, which catches data that does not line up.
  • reversed walks a sequence backwards without copying it, and range(10, 0, -3) counts down in steps of 3.

Sorting, Checking and Transforming

records = [("Nusrat", "CSE", 3.82), ("Arif", "EEE", 3.41), ("Tania", "CSE", 3.95),
           ("Rafi", "EEE", 2.98), ("Mitu", "CSE", 3.67)]

# sorted, min and max accept a key function
print(sorted(records, key=lambda r: r[2], reverse=True)[0])
print(min(records, key=lambda r: r[2])[0], max(records, key=lambda r: len(r[0]))[0])
print([r[0] for r in sorted(records, key=lambda r: (r[1], -r[2]))])

# sum, any and all with generator expressions
print(round(sum(r[2] for r in records) / len(records), 3))
print(any(r[2] < 3.0 for r in records), all(r[2] > 2.5 for r in records))

# map and filter return lazy iterators
names_upper = map(str.upper, (r[0] for r in records))
print(list(names_upper))
print(list(filter(lambda r: r[1] == "EEE", records)))

# divmod, abs, round, pow with a modulus
print(divmod(125, 60), abs(-7), round(2.675, 2), pow(2, 10, 1000))
print(isinstance(3.5, (int, float)), len("Dhaka"), sorted("banana"))

Output

('Tania', 'CSE', 3.95)
Rafi Nusrat
['Tania', 'Nusrat', 'Mitu', 'Arif', 'Rafi']
3.566
True True
['NUSRAT', 'ARIF', 'TANIA', 'RAFI', 'MITU']
[('Arif', 'EEE', 3.41), ('Rafi', 'EEE', 2.98)]
(2, 5) 7 2.67 24
True 5 ['a', 'a', 'a', 'b', 'n', 'n']
  • key= tells sorted, min and max what to compare. key=lambda r: r[2] compares CGPAs, so min found Rafi and the reversed sort put Tania first.
  • Returning a tuple from the key sorts by several things: (r[1], -r[2]) means department A–Z, then CGPA high to low. The minus sign reverses one number field.
  • sum, any and all accept a generator expression, so no temporary list is built. any stops at the first true value and all at the first false one.
  • map and filter return lazy iterators; wrap them in list() to see the values. A list comprehension is often clearer for the same job.
  • divmod(125, 60) gives the quotient and remainder at once (2 hours 5 minutes). pow(2, 10, 1000) computes 210 mod 1000 efficiently.
  • round(2.675, 2) gives 2.67, not 2.68, because 2.675 is stored as a binary number slightly below 2.675. Python also rounds exact halves to the nearest even number, so round(2.5) is 2.

Everyday Built-ins

FunctionUse
len, sum, min, maxSize, total, smallest, largest
sorted, reversedSorted copy, backward iterator
enumerate, zip, rangeLooping helpers
any, allIs any / is every item true?
map, filterTransform or select items lazily
abs, round, divmod, powNumber helpers
int, float, str, list, dict, setConversions and constructors
isinstance, typeCheck an object’s type
input, print, openInput and output

Common Mistakes

  1. Using a built-in’s name as a variable, such as list = [1, 2] or sum = 0. The built-in is then hidden for the rest of that scope.
  2. Using a map or zip result twice. They are iterators and are empty after the first pass. Convert to a list if you need it again.
  3. Writing sorted(data, key=len()). Pass the function itself: key=len.
  4. Calling list.sort() and expecting a result. It sorts in place and returns None; sorted() returns a new list.

Practice Exercises

Exercise 1. Given words = ["mango", "fig", "banana", "kiwi"], find the longest word and sort the words by length, shortest first.

Show answer
print(max(words, key=len))        # banana
print(sorted(words, key=len))     # ['fig', 'kiwi', 'mango', 'banana']

Exercise 2. Two lists hold item prices and quantities. Calculate the total bill in one line.

Show answer
prices = [120, 45, 300]
qty = [2, 4, 1]
print(sum(p * q for p, q in zip(prices, qty, strict=True)))   # 720

Frequently Asked Questions

How can I see every built-in function?

Run import builtins; print(dir(builtins)), or read the “Built-in Functions” page of the official Python documentation. help(zip) shows the documentation for one function.

Should I use map and filter or list comprehensions?

Both work. Most Python developers prefer comprehensions such as [x * 2 for x in nums if x > 0] because they read like a sentence. map is neat when you already have a named function, as in map(str.upper, names).

Summary

  • enumerate and zip make loops cleaner and safer.
  • key= customises sorted, min and max; tuples sort by several fields.
  • any, all and sum work well with generator expressions.
  • Never reuse built-in names such as list, sum or max for variables.

Next: Python itertools Module.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *