Fundamentals 6 min read

10 Elegant Python Tricks to Write Cleaner Code

This article presents ten elegant Python techniques—from multiple assignment and sequence unpacking to ternary expressions, chained comparisons, membership tests, truthiness checks, any/all functions, enumerate, and list comprehensions—showing how to make code more concise and readable.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
10 Elegant Python Tricks to Write Cleaner Code

Assigning Multiple Variables

Conventional method assigns each variable separately, while the elegant method uses tuple unpacking:

a, b, c = 0, 1, 2

Sequence Unpacking

Instead of indexing each element, unpack the list directly:

info = ['brucepk', 'man', 'python']
name, sex, tech = info
print(name, sex, tech)

Elegant Conditional Assignment

Use a ternary expression to assign based on a condition:

x = -6
y = -x if x < 0 else x
print(y)

Chained Comparisons

Replace two separate comparisons with a chained comparison:

score = 82
if 80 <= score < 90:
    level = 'B'
    print(level)

Membership Test with in

Use in to check if a value belongs to a set:

num = 1
if num in (1, 3, 5):
    type = 'odd'
    print(type)

Truthiness Check

Leverage Python's truthiness to test for non‑empty containers without len():

A, B, C = [1, 3, 5], {}, ''
if A:
    print('A is non‑empty')
if B:
    print('B is non‑empty')
if C:
    print('C is non‑empty')

Any vs. Multiple or

Use any() to simplify multiple or conditions:

math, English, computer = 90, 59, 88
if any([math < 60, English < 60, computer < 60]):
    print('not pass')

All vs. Multiple and

Use all() to ensure all conditions are true:

math, English, computer = 90, 80, 88
if all([math > 60, English > 60, computer > 60]):
    print('pass')

Enumerating with Index

Replace manual index handling with enumerate():

L = ['math', 'English', 'computer', 'Physics']
for k, v in enumerate(L):
    print(k, ':', v)

List Comprehension

Generate a list of squares in a single line using a list comprehension: print([x*x for x in range(1, 6)]) Try these elegant patterns to write more readable Python code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

code styleprogramming tipspython basicselegant coding
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

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.