Fundamentals 10 min read

Boost Your Python Skills: 15 Essential Pythonic Tricks Every Developer Should Know

Discover 15 practical Pythonic techniques—from swapping variables and list comprehensions to context managers and chain comparisons—illustrated with clear code examples, while also learning how to claim free Python e-books through a simple WeChat interaction.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Boost Your Python Skills: 15 Essential Pythonic Tricks Every Developer Should Know

Python's concise syntax lets us write code in a human-thinking way, making it easy for beginners and beloved by experts.

To write elegant, Pythonic code, observe seasoned developers; the following common idioms help you develop good habits.

01. Variable swapping

Instead of using a temporary variable:

tmp = a
a = b
b = tmp

You can swap in a single readable line:

a, b = b, a

02. List comprehensions

A simple for loop:

my_list = []
for i in range(10):
    my_list.append(i*2)

Can be replaced by a clear one-line list comprehension:

my_list = [i*2 for i in range(10)]

03. Single-line expressions

Combining multiple statements on one line is not always more Pythonic. For example, the following is discouraged:

print('hello'); print('world')
if x == 1: print('hello,world')
if <complex comparison> and <other complex comparison>:
    # do something

A clearer style separates statements and assigns complex conditions to variables:

print('hello')
print('world')

if x == 1:
    print('hello,world')

cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
    # do something

04. Enumerating with index

Instead of for i in range(len(my_list)), use enumerate:

for i, item in enumerate(my_list):
    print(i, '-->', item)

05. Sequence unpacking

The asterisk operator can unpack a list:

a, *rest = [1, 2, 3]  # a = 1, rest = [2, 3]
a, *middle, c = [1, 2, 3, 4]  # a = 1, middle = [2, 3], c = 4

06. String joining

Joining a list of strings is better done with ''.join():

letters = ['s', 'p', 'a', 'm']
word = ''.join(letters)

07. Truthy / falsy checks

Instead of comparing to True or None, rely on Python's truthiness:

if attr:
    print('attr is truthy!')
if not attr:
    print('attr is falsey!')

08. Dictionary access

Use dict.get() to avoid KeyError:

d = {'hello': 'world'}
print(d.get('hello', 'default_value'))  # prints 'world'
print(d.get('thingy', 'default_value'))  # prints 'default_value'

09. List filtering

Replace explicit loops with list comprehensions or filter:

a = [3, 4, 5]
b = [i for i in a if i > 4]
# or
b = filter(lambda x: x > 4, a)

Higher-order functions like map and reduce are also useful:

b = map(lambda i: i + 3, a)  # b: [6, 7, 8]

10. File handling

Prefer the context manager to ensure files are closed automatically:

with open('file.txt') as fp:
    for line in fp.readlines():
        print(line)

11. Long string continuation

Break long strings using backslashes or parentheses for readability:

long_string = ('For a long time I used to go to bed early. '
               'Sometimes, when I had put out my candle, '
               'my eyes would close so quickly that I had not even '
               'time to say “I’m going to sleep.”')

12. Explicit code

Avoid unnecessary dynamic constructs; prefer explicit definitions:

def make_complex(x, y):
    return {'x': x, 'y': y}

13. Placeholder variables

Use an underscore for values you intentionally ignore:

filename = 'foobar.txt'
basename, _, ext = filename.rpartition('.')

14. Chained comparisons

Python allows concise range checks:

score = 85
if 80 < score < 90:
    print("良好")

15. Ternary operator

Replace simple if‑else assignments with a one‑line expression:

age = 20
type = "adult" if age > 18 else "teenager"

To receive the free Python e‑books, reply with the keyword “送书” to the WeChat public account, add the assistant’s WeChat ID pycharm1314 or scan the QR code, and follow the activity rules posted below.

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.

Pythonpythoniccode-tips
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

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.