Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk5 min

10 Python One-Liners for Cleaner Code—and When They May Be Faster

Ten practical Python idioms for common transformations, checks, sorting, text assembly, and assignment—with caveats about readability, memory, and speed.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python one-liners can make common transformations, checks, and assignments easier to read, but fewer lines do not automatically mean faster code. The examples below replace repetitive scaffolding with familiar idioms; their runtime depends on the workload, Python version, and whether they allocate or stream data.

1. Transform or filter with a list comprehension

Before:

cleaned = []
for value in values:
    if keep(value):
        cleaned.append(clean(value))

After:

cleaned = [clean(value) for value in values if keep(value)]

This creates a new list containing transformed values that pass the condition. It is a good fit when the transformation and filter are simple; for nested conditions or several steps, a regular loop is often easier to scan. As the Python Functional Programming HOWTO notes, “You can of course achieve the same effect with a list comprehension.” Python Functional Programming HOWTO.

2. Build a dictionary with a dictionary comprehension

Before:

by_id = {}
for row in rows:
    by_id[key(row)] = value(row)

After:

by_id = {key(row): value(row) for row in rows}

The result is a new mapping from each computed key to its value. Keep both expressions straightforward: if key creation or value selection needs branching or side effects, use a loop and name the intermediate work. If multiple rows produce the same key, the later value replaces the earlier one.

3. Get an index and item with enumerate()

Before:

index = 0
for item in items:
    print(index, item)
    index += 1

After:

for index, item in enumerate(items):
    print(index, item)

enumerate() yields an index and corresponding value together, starting at zero by default. If you are numbering a human-facing list, use enumerate(items, start=1); that changes the displayed count, not Python’s usual zero-based indexing convention. It iterates rather than constructing a separate list of pairs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Pair parallel inputs with zip()

Before:

pairs = []
for index in range(len(names)):
    pairs.append((names[index], scores[index]))

After (Python 3.10 and later):

pairs = [(name, score) for name, score in zip(names, scores, strict=True)]

zip() produces pairs lazily; the comprehension then materializes those pairs as a list. By default, zip() stops as soon as the shortest input ends, which can silently discard unmatched trailing items. With strict=True, unequal lengths raise ValueError instead. Python’s documentation states, “zip is lazy: The elements won’t be processed until the iterable is iterated on, e.g. by a for loop or by wrapping in a list.” Built-in functions reference. For intentional padding rather than an error, use itertools.zip_longest().

5. Check whether any item matches with any()

Before:

found = False
for record in records:
    if is_valid(record):
        found = True
        break

After:

found = any(is_valid(record) for record in records)

This asks whether at least one record passes the test. The generator expression supplies values one at a time, and any() stops at the first true result. If no records pass—or the input is empty—the result is False.

6. Check that every item matches with all()

Before:

every_valid = True
for record in records:
    if not is_valid(record):
        every_valid = False
        break

After:

every_valid = all(is_valid(record) for record in records)

This asks whether every record passes and stops at the first false result. One edge case matters: all([]) is True. That is the conventional “all items pass” result for an empty collection, but if your application requires at least one record, check that separately.

7. Sort by a field with sorted()

Before:

users.sort(key=lambda user: user.name)
sorted_users = users

After:

sorted_users = sorted(users, key=lambda user: user.name)

sorted() returns a new list and leaves the original list’s order unchanged; the in-place list.sort() method instead changes that list. Sorting an iterable also means building a list, so include the memory cost when working with a large input. Supply a key that gives a consistent comparison for your data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

8. Join string pieces with str.join()

Before:

message = ""
for part in parts:
    if message:
        message += ", "
    message += part

After:

message = ", ".join(parts)

The separator is the string before .join(), and each item must already be a string. For numbers or other objects, convert explicitly, for example ", ".join(str(value) for value in values). Joining a sequence of pieces avoids repeated string concatenation in a loop and expresses the intended separator clearly.

9. Use a generator expression when a consumer can stream values

Before:

squares = [value * value for value in values]
total = sum(squares)

After:

total = sum(value * value for value in values)

The generator expression lets sum() consume each square without first creating a list of all of them. That can reduce temporary memory use for a one-pass calculation. If you need the squares again, or need to inspect them as a collection, build and keep the list instead. A generator is consumed as it is iterated, so it is not a reusable stored result.

10. Swap values with unpacking

Before:

temporary = first
first = second
second = temporary

After:

first, second = second, first

Multiple assignment evaluates the right-hand side before assigning the names, so the original values are exchanged without a temporary variable. Use clear names and keep the values’ roles obvious; compressing a complicated sequence of assignments can make code harder to understand.

Do these one-liners actually make Python faster?

Not by virtue of being short. Some patterns can avoid intermediate allocations, as with a generator expression passed directly to sum(); built-ins may also perform work efficiently. Other examples primarily improve clarity, and a comprehension still creates a list. Actual runtime depends on data size, the operations involved, interpreter version, and how the result is consumed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A preliminary 2022 study, “Does Coding in Pythonic Zen Peak Performance? Preliminary Experiments of Nine Pythonic Idioms at Scale”, reported savings of up to 7,000 MB and 32.25 seconds in selected experiments involving idioms such as list comprehensions, generator expressions, zip(), and itertools.zip_longest(). Those are experimental maxima, not expected gains for every use of these constructs; the study itself identifies real-world settings as an open question.

If speed matters, profile a representative workload on the Python version and data you actually use. Compare equivalent results and behavior, including memory use, rather than treating fewer lines as a benchmark.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep the idiom readable—and avoid a common mutable-list trap

Use a comprehension or compact expression when it makes the operation immediately clear. Prefer a loop when the logic needs several branches, intermediate explanations, error handling, or side effects. The goal is understandable code, not a single physical line.

Also avoid multiplying a mutable inner list when you want independent lists:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
rows = [[]] * 3

That creates three references to the same list, so appending through one position changes what appears at all three. Use a comprehension to create separate lists:

rows = [[] for _ in range(3)]

Each iteration constructs a distinct inner list. This is a useful concise idiom precisely because it preserves the independence that the repeated-reference form does not.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.