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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A Python one-liner is a single expression that performs a common job: filtering a list, pairing values, sorting by a rule, or checking a condition across a collection. The ten patterns below use only built-in functions and the standard library, so you can run every example without installing anything beyond Python itself. For each one you will see the input, the value Python returns, and the point at which a longer, clearer version is the better choice.

Python is, in the words of The Python Tutorial, “an easy to learn, powerful programming language.” Short expressions are one of the features that make it so, but a one-line expression is only useful when a reader can still tell what it does.

How to run these examples

Every example works in the interactive interpreter, which you start by typing python or python3 in a terminal. All ten run on Python 3.10 or newer. Nine of them would also work on older releases; the exception is pairwise, covered in its own section. The official tutorial assumes basic programming knowledge and recommends having an interpreter available for hands-on practice, and Python and its standard library are freely available for the major platforms.

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

Two small habits make the output easier to read. Wrap iterator results in list(...) when you want to see them, because many built-ins return an object that produces values on demand rather than a printed list. And when you paste the code into a script rather than the interpreter, add print(...) around the expression, since a script does not echo values back.

Filtering and transforming lists

Comprehensions are the most common one-line pattern in Python. They read left to right as “take each item, transform it if needed, keep it if the condition holds,” and they always produce a new list.

1. Keep only the even numbers

[n for n in range(10) if n % 2 == 0]

This returns [0, 2, 4, 6, 8]. range(10) produces the integers 0 through 9, the if clause keeps only those whose remainder after dividing by 2 is zero, and the result is a list. The condition is evaluated once per item, so the expression is as long as the logic it describes.

2. Transform every item in a sequence

[n * n for n in range(5)]

This returns [0, 1, 4, 9, 16]. The expression before for is applied to each value in turn. Because the transformation appears first, the comprehension reads as the operation you want to perform, which is why this form is usually clearer than a loop that appends to a list.

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.

Pairing values and positions

Two built-ins cover most cases where you need to keep track of more than one sequence at a time: enumerate attaches a position to each value, and zip combines values from several sequences by their position.

3. Number the items in a list

list(enumerate(['Ada', 'Lin']))

This returns [(0, 'Ada'), (1, 'Lin')]. Counting starts at zero by default. If you are producing numbered output for people, pass a start value:

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

which returns [(1, 'Ada'), (2, 'Lin')]. The index is only a counter; it does not change the items.

4. Pair two sequences item by item

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

This returns [('a', 1), ('b', 2)]. zip takes the first value from each input, then the second, and so on. It stops when the shortest input runs out, so extra items in the longer input are silently dropped. If you need to keep them, use itertools.zip_longest with a fillvalue. Plain zip does not check that the inputs are the same length, so do that check yourself when length matters.

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

Sorting with a rule

5. Sort words by length

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

This returns ['fig', 'pear', 'plum']. The key argument is a function that Python calls on each item; the sort then compares the returned values instead of the items themselves. Here len returns the number of characters, so “fig” comes first. “Pear” and “plum” both have four letters, and sorted is stable, which means they keep their original relative order. sorted also returns a new list and leaves the original unchanged.

Asking yes-or-no questions of data

6. Check whether any value passes a test

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

This returns True, because 12 is greater than 10. any returns True as soon as one item is truthy, and it stops reading the rest of the input at that point. The inner expression is a generator expression, so no intermediate list is built. Two edge cases matter: any on an empty input returns False, and its companion all returns True on an empty input. Those defaults are easy to forget when a list might be empty.

Iterator tools from itertools

The itertools documentation describes a set of iterator building blocks. Their results are iterables, so you turn them into a list only when you need to see or store every value.

7. Flatten one level of nested lists

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

This returns [1, 2, 3, 4, 5]. chain.from_iterable walks through each inner list in order. It removes exactly one level of nesting: a list inside a list inside a list would come out still wrapped once. The official built-ins documentation recommends itertools.chain() for concatenating iterables, and it is the better choice here than repeatedly adding lists together.

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

8. Build a running total

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

This returns [2, 5, 10]. Each value is the sum of everything up to and including that position. If you only need the final total, use sum([2, 3, 5]), which returns 10. accumulate is the tool when the intermediate totals matter, such as a balance after each transaction.

9. Get adjacent pairs

from itertools import pairwise
list(pairwise('PYTHON'))

This returns [('P', 'Y'), ('Y', 'T'), ('T', 'H'), ('H', 'O'), ('O', 'N')]. Each tuple holds an item and the one after it, so a string of six characters yields five pairs. pairwise was added in Python 3.10, and it raises an ImportError on earlier versions. If your code must run on an older interpreter, write the pairs with zip(seq, seq[1:]) for sequences that support slicing, or check your version with python --version before using it.

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

Working with files

10. List the Python files in the current folder

from pathlib import Path
sorted([p.name for p in Path('.').iterdir() if p.suffix == '.py'])

The output depends on the folder you run the command from and the files inside it, so there is no fixed result to quote. In a folder containing tool.py, notes.txt, and app.py, the expression returns ['app.py', 'tool.py']. Path('.') refers to the current working directory, iterdir() yields each entry in it, and .suffix returns the extension such as .py. The sorted call is there because iterdir() returns entries in whatever order the filesystem provides, which varies by platform. The pathlib documentation describes Path as the object-oriented interface for ordinary filesystem paths, and the same code works on Windows, macOS, and Linux, although the folder you pass in will differ.

When the one-liner is the wrong choice

A one-liner earns its place when it states the operation plainly. Stop and write the longer form when a reader would need to decode the expression to follow it. The table below lists the usual trade-offs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Task Compact form Prefer the longer form when
Filter and transform List comprehension The condition needs several named steps, or you must handle errors per item.
Join strings ''.join(parts) You need a separator or formatting per item; sum() raises TypeError on strings, so do not use it for this job.
Flatten lists chain.from_iterable The nesting is deeper than one level; a small recursive function is clearer.
Running totals accumulate You only need the final value, where sum() is simpler.
Find files Path.iterdir() with a filter You need to search subfolders, which Path.rglob() handles, or filter by size or date.

A few rules of thumb keep one-liners readable:

  • Keep one condition or one transformation per expression. Two nested comprehensions are usually a sign to split the work.
  • Name the intermediate value when the expression would otherwise need a comment to explain it.
  • Choose the list form when you need to reuse the result, and the iterator form when you only consume it once.
  • Check the edge cases your data can produce, especially empty inputs, unequal lengths, and missing files.

Where to go next

The Python wiki’s beginner guide lists Python One-Liners by Christian Mayer as a book that teaches readers to read and write one-liners. Editions and prices change, so check current listings before buying. For broader practice with Python in everyday tasks, Automate the Boring Stuff with Python is written by its author as a book about practical automation rather than one-liners.

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.