A collection of useful built-in Python functions that most juniors haven't touched
1️⃣
all and any: a mini rule engine— all(iterable) returns True if all elements are true
— any(iterable) returns True if at least one is true
Example:password = "P@ssw0rd123"
checks = [
len(password) >= 8,
any(c.isdigit() for c in password),
any(c.isupper() for c in password),
]
if all(checks):
print("password is ok")
— You can quickly build readable policy checks without a forest of ifs
2️⃣
enumerate: a handy counter instead of manual indexingInstead of for i in range(len(list)):
users = ["alice", "bob", "charlie"]
for idx, user in enumerate(users, start=1):
print(idx, user)
— You get both the index and the value at once. Less chance to shoot yourself in the foot with off-by-one errors
3️⃣
zip: linking multiple sequencesnames = ["alice", "bob", "charlie"]
scores = [10, 20, 15]
for name, score in zip(names, scores):
print(name, score)
— You can glue several lists into one stream of tuples, do parallel iteration, nicely combine data without manual indices
4️⃣
reversed: reverse without copyingdata = [1, 2, 3, 4]
for x in reversed(data):
print(x)
—
reversed returns an iterator, not a new list, which is convenient when you don't want to allocate extra memory
5️⃣
set and frozenset: uniqueness and fast lookupitems = ["a", "b", "a", "c"]
unique = set(items) # {'a', 'b', 'c'}
if "b" in unique:
...
— A great way to kill duplicates and speed up membership checks, plus frozenset is hashable
👩💻
@DataScience4