Online Tools Toolshu.com Log In Sign Up

Python List Comprehensions and Built-In Functions: Write Less, Do More

Original Author:bhnw Released on 2026-04-09 13:12 1 views Star (0)

Writing Five Lines When One Would Do Is a Python Problem

When you see someone else's Python code doing in one line what took you five, it's not showing off — it's genuinely cleaner and more Pythonic.

This article collects list comprehensions and the most useful built-in functions, with copy-ready code snippets for each.


List Comprehensions

List comprehensions are one of Python's most distinctive features — they replace a for loop with a single expression that builds a list.

Basic syntax:

[expression for element in iterable if condition]

The Basics: Replacing a for Loop

# Traditional approach
squares = []
for x in range(10):
    squares.append(x ** 2)

# List comprehension
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Adding a Filter Condition

# Only square the even numbers
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

# Filter empty strings from a list
words = ["hello", "", "world", "", "python"]
clean = [w for w in words if w]
# ["hello", "world", "python"]

String Processing

names = ["alice", "bob", "charlie"]

# Capitalize each name
capitalized = [name.capitalize() for name in names]
# ["Alice", "Bob", "Charlie"]

# Filter names longer than 3 characters and convert to uppercase
result = [name.upper() for name in names if len(name) > 3]
# ["ALICE", "CHARLIE"]

Nested Comprehensions (Flattening a 2D List)

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flat = [x for row in matrix for x in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

Dict and Set Comprehensions

# Dict comprehension
words = ["apple", "banana", "cherry"]
word_lengths = {word: len(word) for word in words}
# {"apple": 5, "banana": 6, "cherry": 6}

# Set comprehension (auto-deduplicates)
nums = [1, 2, 2, 3, 3, 3]
unique = {x ** 2 for x in nums}
# {1, 4, 9}

Generator Expressions: The Memory-Efficient Version

List comprehensions build the entire list in memory at once. For large datasets, swap [] for () to get a generator that produces elements one at a time:

# List comprehension: all elements in memory immediately
total = sum([x ** 2 for x in range(1000000)])

# Generator expression: elements produced one by one, far less memory
total = sum(x ** 2 for x in range(1000000))  # drop the outer []

The Most Useful Built-In Functions

Python ships with a large set of high-quality built-in functions. Knowing these eliminates a lot of code you'd otherwise have to write yourself.

map(): Apply a Function to Every Element

nums = [1, 2, 3, 4, 5]

# Square each number
squares = list(map(lambda x: x ** 2, nums))
# [1, 4, 9, 16, 25]

# Convert a list of strings to integers
str_nums = ["1", "2", "3"]
int_nums = list(map(int, str_nums))
# [1, 2, 3]

List comprehensions are usually more readable than map, but map is cleaner when pairing with an existing function like int or str.

filter(): Keep Only Matching Elements

nums = [1, -2, 3, -4, 5, -6]

# Keep only positive numbers
positives = list(filter(lambda x: x > 0, nums))
# [1, 3, 5]

# filter(None, ...) removes all falsy values (0, None, empty strings, etc.)
mixed = [0, 1, "", "hello", None, 42]
truthy = list(filter(None, mixed))
# [1, "hello", 42]

zip(): Iterate Over Multiple Lists in Parallel

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]

# Pair them up
pairs = list(zip(names, scores))
# [("Alice", 95), ("Bob", 87), ("Charlie", 92)]

# Use in a for loop
for name, score in zip(names, scores):
    print(f"{name}: {score}")

# Unzip (the reverse of zip)
unzipped_names, unzipped_scores = zip(*pairs)

enumerate(): Loop With an Index

fruits = ["apple", "banana", "cherry"]

# No more range(len(...))
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

# Start numbering from 1
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

sorted() and sort(): Sorting

nums = [3, 1, 4, 1, 5, 9, 2, 6]

# sorted() returns a new list, leaves the original untouched
asc = sorted(nums)                  # [1, 1, 2, 3, 4, 5, 6, 9]
desc = sorted(nums, reverse=True)   # [9, 6, 5, 4, 3, 2, 1, 1]

# sort() sorts in place and returns None
nums.sort()

# Sort by a custom key
words = ["banana", "apple", "cherry", "date"]
by_length = sorted(words, key=len)
by_second_letter = sorted(words, key=lambda w: w[1])

# Sort a list of dicts by a field
users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
by_age = sorted(users, key=lambda u: u["age"])

any() and all(): Bulk Logic Checks

nums = [1, 2, 3, 4, 5]

# any(): at least one element is truthy
has_even = any(x % 2 == 0 for x in nums)   # True
has_negative = any(x < 0 for x in nums)     # False

# all(): every element is truthy
all_positive = all(x > 0 for x in nums)     # True
all_even = all(x % 2 == 0 for x in nums)    # False

# Practical use: check that all form fields are filled
fields = {"name": "Alice", "email": "alice@example.com", "age": 28}
is_complete = all(fields.values())   # True (all values are truthy)

min() and max(): Finding Extremes

nums = [3, 1, 4, 1, 5, 9]
print(min(nums))   # 1
print(max(nums))   # 9

# With a key function
words = ["banana", "apple", "cherry"]
shortest = min(words, key=len)   # "apple"
longest = max(words, key=len)    # "banana" or "cherry"

# Find the extreme in a list of dicts
users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
youngest = min(users, key=lambda u: u["age"])
# {"name": "Alice", "age": 25}

sum(): Summation

nums = [1, 2, 3, 4, 5]
print(sum(nums))          # 15
print(sum(nums, 100))     # 115 (starts accumulating from 100)

# Sum a nested list
matrix = [[1, 2], [3, 4], [5, 6]]
total = sum(sum(row) for row in matrix)   # 21

isinstance(): Type Checking

x = 42

print(isinstance(x, int))           # True
print(isinstance(x, str))           # False
print(isinstance(x, (int, float)))  # True (matches either)

# Practical: validate function arguments
def process(data):
    if not isinstance(data, (list, tuple)):
        raise TypeError(f"Expected list or tuple, got {type(data).__name__}")
    return [x * 2 for x in data]

round(), abs(), divmod()

# round(): rounds to n decimal places
round(3.14159, 2)   # 3.14
round(3.5)          # 4
round(2.5)          # 2 (Python 3 uses banker's rounding — rounds to even)

# abs(): absolute value
abs(-5)    # 5
abs(-3.14) # 3.14

# divmod(): quotient and remainder in one call
q, r = divmod(17, 5)   # q=3, r=2

One-Liner Quick Reference

A few frequently useful single-line patterns worth bookmarking:

# Deduplicate a list (order-preserving)
seen = set()
unique = [x for x in lst if not (x in seen or seen.add(x))]

# Deduplicate without preserving order
unique = list(set(lst))

# Flatten one level of nesting
flat = [x for sublist in nested for x in sublist]

# Count element occurrences
from collections import Counter
counts = Counter(["a", "b", "a", "c", "b", "a"])
# Counter({"a": 3, "b": 2, "c": 1})

# Merge two dicts (Python 3.9+)
merged = dict1 | dict2

# Swap two variables
a, b = b, a

# Check if a list is empty
if not my_list:
    print("list is empty")

Want to run these snippets and verify the output right now? Paste them into the Online Python Runner — Python 3.12, full standard library, results appear the moment you hit Ctrl+Enter.

发现周边 发现周边
Comment area

Loading...