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 DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk6 min

10 Python One-Liners That Will Blow Your Mind (With Real Examples)

Ten compact Python patterns with exact inputs and outputs, covering built-ins, itertools and pathlib, plus guidance on when a longer, readable version is better.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ten short Python expressions cover a lot of everyday work: filtering a list, pairing values with their positions, sorting by a custom rule, checking a condition across a collection, and listing files. Each example below shows the exact input, the value Python returns, and the point where a longer version is the better choice. Every snippet runs in a Python 3 interpreter, and one of them needs Python 3.10 or later.

Before you run the examples

You need a Python interpreter. The official Python Tutorial says Python and its standard library are freely available for major platforms, and it describes the language this way: “Python is an easy to learn, powerful programming language.” (The Python Tutorial, version 3.14) Open a terminal, type python3 (or python on Windows), and you get the interactive prompt, >>>. Paste each line after the prompt and compare what you see with the output shown below it.

The examples use built-in functions, which are available without any import. Built-ins are documented on the built-in functions page for version 3.13. A few examples use tools from itertools and pathlib, and each of those is marked with its import line.

Building lists in one expression

A list comprehension has the shape [expression for item in iterable if condition]. Python reads it left to right: take each item, optionally keep it if the condition is true, and collect the results into a new list.

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

1. Filter even numbers

>>> [n for n in range(10) if n % 2 == 0]
[0, 2, 4, 6, 8]

range(10) produces 0 through 9. The if clause keeps only the values whose remainder after division by 2 is zero. The input is never changed; a new list is returned.

2. Square every value in a sequence

>>> [n * n for n in range(5)]
[0, 1, 4, 9, 16]

This version has no if clause, so every value is transformed. If you replace the square brackets with parentheses, you get a generator expression. It yields values one at a time instead of building a list, which matters when the input is large. The built-in docs describe generator expressions alongside comprehensions in the same built-in functions reference.

Pairing values with positions and with other sequences

3. Number items with enumerate

>>> list(enumerate(['Ada', 'Lin']))
[(0, 'Ada'), (1, 'Lin')]
>>> list(enumerate(['Ada', 'Lin'], start=1))
[(1, 'Ada'), (2, 'Lin')]

enumerate returns an iterator of (index, item) pairs. Counting starts at zero unless you pass start. Use start=1 when the numbers will be shown to people, such as in a numbered menu. The list(...) wrapper is only there so you can see the values; the function itself produces them lazily.

4. Pair two sequences by position

>>> list(zip(['a', 'b'], [1, 2]))
[('a', 1), ('b', 2)]
>>> list(zip('abc', [1, 2]))
[('a', 1), ('b', 2)]

zip matches values by position. The second example shows the catch: when the inputs have different lengths, zip stops at the shortest one and does not warn you. The letter 'c' is silently dropped. If that could hide a bug in your data, check the lengths before zipping.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Sorting and asking yes-or-no questions

5. Sort words by length

>>> sorted(['pear', 'fig', 'plum'], key=len)
['fig', 'pear', 'plum']

sorted returns a new list and leaves the original alone. The key argument is a function applied to each item before comparison; here len measures each word, so the words are ordered by character count. Words of equal length, such as pear and plum, keep their original relative order because Python’s sort is stable.

6. Check whether any value passes a threshold

>>> any(n > 10 for n in [3, 12, 7])
True
>>> any(n > 10 for n in [])
False

any returns True as soon as one item is truthy and False otherwise. The generator expression stops evaluating at the first match, which is useful when checking a long or expensive sequence. The empty-list case is worth remembering: any over nothing is False, so a check that expects at least one match should not rely on any alone when the input might be empty.

Iterator tools from itertools

The itertools documentation describes these functions as iterator building blocks. Their results are iterators, so you wrap them in list(...) only when you need to see or store every value at once. If you loop over the result directly, you can skip the wrapper.

7. Flatten one level of nested lists

>>> from itertools import chain
>>> list(chain.from_iterable([[1, 2], [3], [4, 5]]))
[1, 2, 3, 4, 5]

chain.from_iterable takes an iterable of iterables and yields the items of each in turn. It removes exactly one level of nesting. A list inside a list inside a list stays nested. For string concatenation, the built-in docs recommend ''.join(sequence) over sum(), while itertools.chain() is the recommended tool for concatenating iterables.

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

A readable alternative, useful when the nesting is deeper or you want to add logic inside the loop:

nested = [[1, 2], [3], [4, 5]]
flat = []
for part in nested:
    flat.extend(part)
print(flat)   # [1, 2, 3, 4, 5]

8. Build a running total

>>> from itertools import accumulate
>>> list(accumulate([2, 3, 5]))
[2, 5, 10]

accumulate yields each partial result: 2, then 2 + 3, then 2 + 3 + 5. The last value is the total, which is what sum([2, 3, 5]) returns on its own. Use accumulate when you need the intermediate totals, such as a cumulative balance chart. Use sum when only the final figure matters.

9. Get adjacent pairs

>>> from itertools import pairwise
>>> list(pairwise('PYTHON'))
[('P', 'Y'), ('Y', 'T'), ('T', 'H'), ('H', 'O'), ('O', 'N')]

pairwise yields each item together with the one after it. A list of n items produces n minus one pairs, so the result is one shorter than the input. This is the example to check first if your Python is older: pairwise is not available before Python 3.10. On an older release, the import fails with an ImportError. You can confirm the version with python3 --version, and the itertools reference lists the function’s documented behavior.

Listing files from a folder

10. List Python files in the current directory

>>> from pathlib import Path
>>> [p.name for p in Path('.').iterdir() if p.suffix == '.py' and p.is_file()]
['helpers.py', 'main.py']

Path('.') refers to the folder Python was started from, which is not always the folder your script lives in. The output depends on that folder and its contents, so the list above is only an example; your result will differ. Two details make the expression safer. The p.is_file() check excludes folders whose names happen to end in .py. The order of iterdir() results is arbitrary, so wrap the expression in sorted(...) if you need a stable listing.

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

The pathlib documentation for version 3.14 describes Path as the object-oriented interface to filesystem paths. Behavior can vary across operating systems and folder permissions, so test the expression in the folder you actually plan to use.

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

Quick reference

# Pattern Import needed What it returns Version note
1 Filter with a comprehension None List None noted
2 Transform with a comprehension None List None noted
3 enumerate None Iterator of (index, item) pairs None noted
4 zip None Iterator of tuples; stops at shortest input None noted
5 sorted with key None New list None noted
6 any None Boolean None noted
7 chain.from_iterable from itertools import chain Iterator; removes one level of nesting None noted
8 accumulate from itertools import accumulate Iterator of running totals None noted
9 pairwise from itertools import pairwise Iterator of adjacent pairs Python 3.10 or later
10 Path.iterdir with filter from pathlib import Path List of file names; depends on folder contents None noted

When the one-liner is the wrong choice

A one-liner earns its place when the operation is familiar to anyone reading the code: filtering, pairing, or summing. It stops earning its place when a reader has to decode it. Keep the compact form when a single transformation fits on one line and the names are self-explanatory. Switch to a loop or named intermediate variables when any of the following is true:

  • The expression needs more than one condition or nested comprehension.
  • The loop body has side effects, such as writing files or updating a counter.
  • You need error handling or logging for individual items.
  • The empty-input case has a different meaning from the populated case, as with any([]) returning False.

In practice, the best one-liner is often two readable lines. Name the intermediate result, and let the next line use it.

Where to go next

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.

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

Leave a Reply

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

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
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.