Python any() and all() Examples
Short, runnable programs that show python any() and all() in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python any() and all() lesson.
1Blocking comments with banned words
any() replaces a long chain of or tests. Lowercasing the comment first makes the match case-insensitive.
banned = ["spam", "scam", "free money"]
comments = ["Great lesson, thanks!", "Get FREE MONEY now", "This is a scam"]
for comment in comments:
text = comment.lower()
flagged = any(word in text for word in banned)
print("blocked" if flagged else "ok", "-", comment)Expected outputok - Great lesson, thanks!
blocked - Get FREE MONEY now
blocked - This is a scam
2Checking a tic-tac-toe board with nested any and all
all() asks whether every cell of a line holds an X, and the outer any() asks whether any row or column is such a line. Combining the two is natural once each reads as a sentence.
board = [
["X", "O", "X"],
["O", "X", "X"],
["O", "O", "X"],
]
row_win = any(all(cell == "X" for cell in row) for row in board)
column_win = any(all(row[i] == "X" for row in board) for i in range(3))
diagonal_win = all(board[i][i] == "X" for i in range(3))
print("Row win:", row_win)
print("Column win:", column_win)
print("Diagonal win:", diagonal_win)Expected outputRow win: False
Column win: True
Diagonal win: True
3Counting matches with sum()
A comparison gives True or False, and True counts as 1, so sum() adds up the matches. Dividing by len() turns the count into a percentage.
attendance = ["present", "absent", "present", "present", "late", "present"]
present = sum(status == "present" for status in attendance)
late_or_absent = sum(1 for status in attendance if status != "present")
print(present, "present,", late_or_absent, "late or absent")
print(f"Attendance: {present / len(attendance):.0%}")Expected output4 present, 2 late or absent
Attendance: 67%
4The first match, with a fallback
next() pulls one item out of a generator expression and stops there, so the rest of the list is never examined. The second argument is returned when nothing matches.
invoices = [("INV-1", 0), ("INV-2", 12), ("INV-3", 30)] # (id, days overdue)
first_overdue = next((inv for inv, days in invoices if days > 0), None)
print(first_overdue)
print(next((inv for inv, days in invoices if days > 90), "none"))Expected outputINV-2
none
5min() and max() with key and default
key= tells min and max what to compare, here each item's price. default= is what you get for an empty collection instead of a ValueError.
prices = {"pen": 1.5, "ink": 8.0, "tape": 2.25, "stapler": 9.25}
in_stock = ["ink", "tape", "stapler"]
print(min(in_stock, key=prices.get))
print(max(in_stock, key=prices.get))
print(min([], key=prices.get, default="nothing in stock"))Expected outputtape
stapler
nothing in stock
6Is a list sorted? all() over neighbouring pairs
zip(values, values[1:]) pairs each item with the one after it, and all() checks every pair. Lists with zero or one item have no pairs, so they count as sorted.
def is_sorted(values):
return all(a <= b for a, b in zip(values, values[1:]))
print(is_sorted([1, 3, 3, 8]))
print(is_sorted([4, 2, 9]))
print(is_sorted([]), is_sorted([7]))Expected outputTrue
False
True True
Practise next
Python any() and all() exercises → Back to the lesson
Python Logical Conditions examplesPython Truthy and Falsy Values examplesPython Generators, Iterators and yield examplesPython map, filter and reduce examples