Fundamentals 10 min read

What Makes Code Truly Pythonic? 20 Idiomatic Examples Explained

This article explains the concept of "pythonic" code in Python, comparing concise, readable idioms with longer non‑pythonic alternatives across common tasks such as swapping variables, truth testing, string manipulation, list operations, comprehensions, dictionary handling, loop control, ternary expressions, enumerate, and zip.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
What Makes Code Truly Pythonic? 20 Idiomatic Examples Explained

What is Pythonic?

In Chinese, "pythonic" translates to "very Python" and conveys a special emphasis, meaning a way of writing code that only Python can do, distinct from other languages—essentially Python’s idiomatic and unique style.

Swapping Two Variables

Pythonic: a,b = b,a Non‑pythonic:

temp = a
a = b
b = temp

The tuple pack/unpack avoids a temporary variable and uses a single line.

Chain Comparison

Pythonic:

a = 3
b = 1
1 <= b <= a < 10  # True

Non‑pythonic: b >= 1 and b <= a and a < 10 # True The Pythonic form is clearer and shorter.

Truth Testing

Pythonic:

name = 'Tim'
langs = ['AS3', 'Lua', 'C']
info = {'name': 'Tim', 'sex': 'Male', 'age': 23}
if name and langs and info:
    print('All True!')

Non‑pythonic:

if name != '' and len(langs) > 0 and info != {}:
    print('All True!')

Direct truth testing reduces code and improves readability.

String Reversal

Pythonic:

def reverse_str(s):
    return s[::-1]

Non‑pythonic:

def reverse_str(s):
    t = ''
    for x in xrange(len(s)-1, -1, -1):
        t += s[x]
    return t

The slice notation is both elegant and efficient.

Joining a List of Strings

Pythonic:

strList = ["Python", "is", "good"]
res = ' '.join(strList)  # Python is good

Non‑pythonic:

res = ''
for s in strList:
    res += s + ' '
# Result has an extra trailing space

Using join is faster and avoids errors.

List Summation, Max, Min, Product

Pythonic:

numList = [1,2,3,4,5]
sum_val = sum(numList)
max_val = max(numList)
min_val = min(numList)
from operator import mul
prod = reduce(mul, numList, 1)

Non‑pythonic:

sum_val = 0
max_val = -float('inf')
min_val = float('inf')
prod = 1
for num in numList:
    if num > max_val:
        max_val = num
    if num < min_val:
        min_val = num
    sum_val += num
    prod *= num

Benchmarks show the Pythonic version can be twice as fast on large lists.

List Comprehension

Pythonic:

l = [x*x for x in range(10) if x % 3 == 0]  # [0, 9, 36, 81]

Non‑pythonic:

l = []
for x in range(10):
    if x % 3 == 0:
        l.append(x*x)

The comprehension is concise and expressive.

Dictionary Default Value

Pythonic:

dic = {'name':'Tim', 'age':23}
dic['workage'] = dic.get('workage', 0) + 1

Non‑pythonic:

if 'workage' in dic:
    dic['workage'] += 1
else:
    dic['workage'] = 1
get(key, default)

eliminates the explicit if…else check.

For‑else Loop

Pythonic:

for x in xrange(1,5):
    if x == 5:
        print 'find 5'
        break
else:
    print 'can not find 5!'

Non‑pythonic:

found = False
for x in xrange(1,5):
    if x == 5:
        found = True
        print 'find 5'
        break
if not found:
    print 'can not find 5!'

The for‑else construct handles the no‑break case without extra flags.

Ternary Alternative

Pythonic:

a = 3
b = 2 if a > 2 else 1

Non‑pythonic:

if a > 2:
    b = 2
else:
    b = 1

Using the inline conditional expression is clearer and avoids mis‑behaving logical tricks.

Enumerate

Pythonic:

array = [1,2,3,4,5]
for i, e in enumerate(array, 0):
    print i, e

Non‑pythonic:

for i in xrange(len(array)):
    print i, array[i]
enumerate

yields index and value directly and supports a custom start index.

Creating Key‑Value Pairs with zip

Pythonic:

keys = ['Name', 'Sex', 'Age']
values = ['Tim', 'Male', 23]
dic = dict(zip(keys, values))  # {'Name': 'Tim', 'Sex': 'Male', 'Age': 23}

Non‑pythonic:

dic = {}
for i, e in enumerate(keys):
    dic[e] = values[i]
zip

creates tuples that can be turned into a dictionary in one step.

References

Writing Idiomatic Python

Python Idioms

Code Like a Pythonista: Idiomatic Python

Code Style — The Hitchhiker’s Guide to Python

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.

programmingcode styleexamplespythonicidiomatic
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.