Fundamentals 9 min read

Common Python One‑Line Code Snippets and Tricks

This article presents a collection of concise Python one‑line code snippets—including ternary operators, multiple variable assignments, list swapping, list comprehensions, dictionary and set comprehensions, file handling, and command‑line one‑liners—demonstrating how to write more compact and readable code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Common Python One‑Line Code Snippets and Tricks

Python allows powerful operations with short code snippets. This article shares some of the most popular Python one‑line codes that are widely used in the community for their brevity and clarity.

Ternary Operator

The ternary operator computes a value based on a condition without needing a multi‑line if/else statement.

<code>x = 1
y = 2
z = 1 if x > 0 and y > x else -1
print(z)</code>

Multiple Variable Assignment

Assign values to several variables simultaneously.

<code>x, y = "Python", 123
print(x, y)</code>

Swapping Variable Values

Swap the values of two variables without a temporary variable.

<code>x, y = "Python", 123
x, y = y, x
print(x, y)</code>

Swapping List Elements

Swap the first and last elements of a list, or swap elements at even and odd positions using slicing.

<code>x = [1, 2, 3, 4, 5, 6]
x[0], x[5] = x[5], x[0]
print(x)  # [6, 2, 3, 4, 5, 1]

x = [1, 2, 3, 4, 5, 6]
x[::2], x[1::2] = x[1::2], x[::2]
print(x)  # [2, 1, 4, 3, 6, 5]
</code>

Replacing List Elements

Replace every element at odd positions (or even positions) with a constant, e.g., 0.

<code>x = [1, 2, 3, 4, 5, 6]
x[1::2] = [0] * len(x[1::2])
print(x)  # [1, 0, 3, 0, 5, 0]
</code>

List Comprehension with Ternary Operator

<code>x = [1, 2, 3, 4, 5, 6]
y = [z if i % 2 == 0 else 0 for i, z in enumerate(x)]
print(y)  # [1, 0, 3, 0, 5, 0]
</code>

Using List Comprehensions

Generate a new list with specific filtering conditions, such as all even numbers between 1 and 20.

<code>n = [i for i in range(1, 20) if i % 2 == 0]
print(n)
</code>

Creating Sublist from List

Extract a sublist from an existing list using a comprehension.

<code>x = [1, 2, 3, 4, 5, 6]
y = [i for i in x if i < 4]
print(y)  # [1, 2, 3]
</code>

Changing List Element Types

Convert list elements to another type, such as turning integers into characters and then to lowercase.

<code>x = [1, 2, 3, 4, 5, 6]
y = [chr(65 + i) for i in x]
z = [i.lower() for i in y]
print(y)  # ['B', 'C', 'D', 'E', 'F', 'G']
print(z)  # ['b', 'c', 'd', 'e', 'f', 'g']
</code>

List Comprehension to List Files

Traverse the current directory and list all ".xlsx" files.

<code>import os
x = [f for d in os.walk(".") for f in d[2] if f.endswith(".xlsx")]
print(x)
</code>

Flattening Multidimensional List

Flatten a nested list into a one‑dimensional list using a comprehension or itertools .

<code>a = [[1,2], [3,4], [5,6]]
b = [y for x in a for y in x]
print(b)  # [1, 2, 3, 4, 5, 6]

import itertools
a = [[1,2], [3,4], [5,6]]
b = list(itertools.chain.from_iterable(a))
print(b)  # [1, 2, 3, 4, 5, 6]
</code>

Dictionary Comprehension

Create a dictionary from a list using a comprehension.

<code>x = [1, 2, 3, 4, 5, 6]
dict1 = {chr(65 + i): v + 65 for i, v in enumerate(x)}
print(dict1)  # {'A': 66, 'B': 67, 'C': 68, 'D': 69, 'E': 70, 'F': 71}
</code>

Set Comprehension

Generate a set from a list and remove duplicate values.

<code>x = [1, 2, 3, 4, 5, 6]
set1 = {chr(65 + i) for i in x}
print(set1)  # {'A', 'B', 'C', 'D', 'E', 'F'}

x = [1, 2, 2, 4, 5, 5]
y = set(x)
print(y)  # {1, 2, 4, 5}
</code>

Reading File into Generator

Read the contents of test.txt line by line using a generator expression.

<code>text = (line.strip() for line in open('test.txt', 'r'))
print(text)  # <generator object <genexpr> at 0x...>
print(list(text))  # ['1', '2', '3', '4', '5', '6']
</code>

One‑Line Python -c Commands

Execute short Python snippets directly from the command line without entering the interactive interpreter.

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

These one‑line codes can greatly improve readability and coding efficiency, though performance considerations should also be taken into account.

code snippetsternary operatorOne‑Linerlist comprehension
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.