Common Built-in Functions#
Python’s built-in functions don’t require import — they’re available directly. This article covers the most commonly used functions for working with sequence data.
zip()#
zip() pairs elements from multiple iterables into tuples, returning an iterator:
1
2
3
4
5
6
7
8
9
| names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score} points")
# Alice: 85 points
# Bob: 92 points
# Charlie: 78 points
|
Pair multiple sequences#
1
2
3
4
5
6
| names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
cities = ["Taipei", "Kaohsiung", "Taichung"]
for name, score, city in zip(names, scores, cities):
print(f"{name} ({city}): {score} points")
|
When lengths differ#
zip() stops at the shortest sequence; extra elements are ignored. Use itertools.zip_longest() to fill missing values:
1
2
3
4
5
6
7
8
9
10
| from itertools import zip_longest
list1 = [1, 2, 3]
list2 = ["a", "b"]
print(list(zip(list1, list2)))
# [(1, 'a'), (2, 'b')]
print(list(zip_longest(list1, list2, fillvalue="?")))
# [(1, 'a'), (2, 'b'), (3, '?')]
|
Build a dictionary#
1
2
3
4
5
6
| keys = ["name", "age", "city"]
values = ["Alice", 25, "Taipei"]
person = dict(zip(keys, values))
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'Taipei'}
|
Unzip#
Use zip(*iterable) to restore the original sequences:
1
2
3
4
5
| pairs = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
names, scores = zip(*pairs)
print(names) # ('Alice', 'Bob', 'Charlie')
print(scores) # (85, 92, 78)
|
Transpose a matrix#
1
2
3
4
5
6
7
8
9
10
11
12
13
| matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
transposed = list(zip(*matrix))
for row in transposed:
print(row)
# (1, 4, 7)
# (2, 5, 8)
# (3, 6, 9)
|
enumerate()#
enumerate() gives you both the index and value during iteration, avoiding manual counters:
1
2
3
4
5
6
7
8
9
10
11
12
13
| fruits = ["apple", "banana", "cherry"]
# Traditional approach
for i in range(len(fruits)):
print(i, fruits[i])
# Using enumerate (more Pythonic)
for i, fruit in enumerate(fruits):
print(i, fruit)
# 0 apple
# 1 banana
# 2 cherry
|
Custom start index#
1
2
3
4
5
6
| for i, fruit in enumerate(fruits, start=1):
print(f"Item {i}: {fruit}")
# Item 1: apple
# Item 2: banana
# Item 3: cherry
|
Find indices matching a condition#
1
2
3
4
| scores = [72, 85, 60, 91, 55, 88]
failing = [i for i, s in enumerate(scores) if s < 60]
print(failing) # [4] (score 55 at index 4 is a failing grade)
|
map()#
map() applies a function to each element of a sequence and returns an iterator:
1
2
3
4
5
6
7
| numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25]
# Equivalent to list comprehension (recommended)
squares = [x ** 2 for x in numbers]
|
With a named function#
1
2
3
4
5
6
| def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
temps_c = [0, 20, 37, 100]
temps_f = list(map(celsius_to_fahrenheit, temps_c))
print(temps_f) # [32.0, 68.0, 98.6, 212.0]
|
Process multiple sequences simultaneously#
1
2
3
4
5
| a = [1, 2, 3]
b = [10, 20, 30]
result = list(map(lambda x, y: x + y, a, b))
print(result) # [11, 22, 33]
|
filter()#
filter() selects elements that match a condition and returns an iterator:
1
2
3
4
5
6
7
| numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
# Equivalent to list comprehension (recommended)
evens = [x for x in numbers if x % 2 == 0]
|
Filter non-empty strings#
1
2
3
| words = ["hello", "", "world", "", "python"]
non_empty = list(filter(None, words)) # None filters out falsy values
print(non_empty) # ['hello', 'world', 'python']
|
sorted() with key#
sorted() returns a new sorted list. The key parameter lets you customize the sort order:
1
2
3
4
5
6
7
8
9
10
11
12
13
| words = ["banana", "apple", "cherry", "kiwi"]
# Default alphabetical order
print(sorted(words))
# ['apple', 'banana', 'cherry', 'kiwi']
# Sort by length
print(sorted(words, key=len))
# ['kiwi', 'apple', 'banana', 'cherry']
# Descending
print(sorted(words, key=len, reverse=True))
# ['banana', 'cherry', 'apple', 'kiwi']
|
Sort a list of dicts#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| students = [
{"name": "Alice", "score": 85, "age": 20},
{"name": "Bob", "score": 92, "age": 22},
{"name": "Charlie", "score": 85, "age": 21},
]
# Sort by score descending
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
for s in by_score:
print(f"{s['name']}: {s['score']}")
# Bob: 92
# Alice: 85
# Charlie: 85
|
Multi-condition sorting#
1
2
3
4
5
6
7
8
9
10
11
| # When scores are equal, sort by age ascending
by_score_then_age = sorted(
students,
key=lambda s: (-s["score"], s["age"])
)
for s in by_score_then_age:
print(f"{s['name']}: {s['score']}, age {s['age']}")
# Bob: 92, age 22
# Alice: 85, age 20
# Charlie: 85, age 21
|
any() and all()#
any(): returns True if any element satisfies the condition#
1
2
3
4
5
6
7
| scores = [72, 85, 60, 91, 55]
# Does anyone have a perfect score?
print(any(s == 100 for s in scores)) # False
# Does anyone have a failing grade?
print(any(s < 60 for s in scores)) # True
|
all(): returns True only if all elements satisfy the condition#
1
2
3
4
5
6
| # Did everyone pass?
print(all(s >= 60 for s in scores)) # False
# Validate all inputs are positive integers
inputs = [3, 7, 2, 9]
print(all(isinstance(x, int) and x > 0 for x in inputs)) # True
|
min() and max() with key#
1
2
3
4
5
6
7
8
9
10
11
| students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78},
]
best = max(students, key=lambda s: s["score"])
worst = min(students, key=lambda s: s["score"])
print(f"Highest score: {best['name']} ({best['score']})") # Bob (92)
print(f"Lowest score: {worst['name']} ({worst['score']})") # Charlie (78)
|
Comprehensive Example: Grade Analysis#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| students = [
("Alice", [85, 92, 78]),
("Bob", [70, 88, 95]),
("Charlie", [60, 55, 72]),
]
# Calculate average per person and add to results
with_avg = [
(name, scores, round(sum(scores) / len(scores), 1))
for name, scores in students
]
# Sort by average descending
ranked = sorted(with_avg, key=lambda x: x[2], reverse=True)
print("=== Grade Rankings ===")
for rank, (name, scores, avg) in enumerate(ranked, start=1):
status = "Pass" if avg >= 60 else "Fail"
print(f"#{rank} | {name} | Avg {avg} | {status}")
# Did everyone pass?
all_pass = all(avg >= 60 for _, _, avg in with_avg)
print(f"\nAll passed: {all_pass}")
|
Output:
=== Grade Rankings ===
#1 | Alice | Avg 85.0 | Pass
#2 | Bob | Avg 84.3 | Pass
#3 | Charlie | Avg 62.3 | Pass
All passed: True