15 Powerful Python One-Liners Every Beginner Should Know

Python enables concise yet expressive code through clever one-liners that simplify common programming tasks.

Conditional Assignment with Ternary Operator

Assign a value based on a condition without using multi-line if-else blocks:

a = 10
b = 20
result = a if a > b else b
print(result)  # 20

Multiple Variable Assignment

Initialize several variables in a single line:

name, age = "Alice", 30
print(name, age)

Swappign Variables

Exchange values between two variables without a temporary placeholder:

x, y = 5, 10
x, y = y, x
print(x, y)  # 10 5

Swapping List Elements

Swap the first and last elements of a list using index assignment:

items = [1, 2, 3, 4, 5]
items[0], items[-1] = items[-1], items[0]
print(items)  # [5, 2, 3, 4, 1]

Interleaved Element Swap

Swap adjacent pairs (even-indexed with odd-indexed elements):

seq = [1, 2, 3, 4, 5, 6]
seq[::2], seq[1::2] = seq[1::2], seq[::2]
print(seq)  # [2, 1, 4, 3, 6, 5]

Replace Elements at Specific Indices

Set all odd-positioned elements (1-based even indices) to zero:

values = [1, 2, 3, 4, 5, 6]
values[1::2] = [0] * len(values[1::2])
print(values)  # [1, 0, 3, 0, 5, 0]

Conditional List Construction

Use list comprehension with a ternary expression to selcetively transform elements:

original = [1, 2, 3, 4, 5, 6]
modified = [val if idx % 2 == 0 else 0 for idx, val in enumerate(original)]
print(modified)  # [1, 0, 3, 0, 5, 0]

Filtered List Generation

Create a list of even numbers from 1 to 19:

evens = [n for n in range(1, 20) if n % 2 == 0]
print(evens)

Sublist Creation

Extract elements less than 4 from an existing list:

source = [1, 2, 3, 4, 5, 6]
subset = [x for x in source if x < 4]
print(subset)  # [1, 2, 3]

Type Conversion via Comprehension

Convert integers to uppercase letters, then to lowercase:

nums = [0, 1, 2, 3, 4, 5]
upper_chars = [chr(65 + i) for i in nums]
lower_chars = [c.lower() for c in upper_chars]
print(lower_chars)  # ['a', 'b', 'c', 'd', 'e', 'f']

Alternatively, using map:

nums = [0, 1, 2, 3, 4, 5]
upper = list(map(lambda i: chr(65 + i), nums))
lower = list(map(str.lower, upper))

File Listing with Comprehension

List all .xlsx files in the current directory and subdirectories:

import os
xlsx_files = [f for root, _, files in os.walk(".") for f in files if f.endswith(".xlsx")]
print(xlsx_files)

Flattening Nested Lists

Flatten a 2D list into a 1D list:

nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
print(flat)  # [1, 2, 3, 4, 5, 6]

Or using itertools:

import itertools
flat = list(itertools.chain.from_iterable(nested))

Dictionary Comprehension

Map characters to offset values:

keys = [0, 1, 2, 3, 4, 5]
mapping = {chr(65 + i): v + 65 for i, v in enumerate(keys)}
print(mapping)  # {'A': 65, 'B': 66, ..., 'F': 70}

Set Comprehension and Deduplication

Generate a set of letters or remove duplicates:

indices = [1, 2, 3, 4, 5, 6]
letters = {chr(65 + i) for i in indices}
print(letters)  # {'B', 'C', 'D', 'E', 'F', 'G'}

duplicates = [1, 2, 2, 4, 5, 5]
unique = set(duplicates)
print(unique)  # {1, 2, 4, 5}

Lazy File Reading with Generator Expression

Read lines from a file lazily:

lines = (line.strip() for line in open('test.txt'))
print(list(lines))

Executing Code via Command Line

Run Python snippets directly from the terminal:

python -c "import sys; print(sys.version.split()[0])"
python -c "import os; print(os.getenv('PATH').split(';'))"

Tags: python one-liners list-comprehension coding-tips Beginner

Posted on Tue, 23 Jun 2026 16:57:30 +0000 by *mt