Fundamentals 6 min read

8 Handy Python Tricks for Better Code Readability and Efficiency

This article presents eight practical Python tips—including using underscores for large numbers, creating immutable sets, swapping dictionary keys and values, generating specific ranges of numbers, safely accessing missing keys, locating installed modules, extracting middle list elements, and unpacking list items into variables—each illustrated with clear code examples and expected outputs.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
8 Handy Python Tricks for Better Code Readability and Efficiency

1. Use underscores to separate large numbers – Improves human readability of big integers. Example: num = 1000000000 Formatted versions:

num1 = 1_000_000_000  # Western style
num2 = 10_0000_0000  # Chinese style

Both print as 1000000000 1000000000.

2. Convert a list to an immutable "frozenset" – frozenset is hashable and cannot be modified, making it usable as a dictionary key.

f_set = frozenset([1, 2, 3, 4])
for n in f_set:
    print(n)

Output:

1
2
3
4

To convert back to a mutable list and add elements:

lst = list(f_set)
lst.append(5)
print(lst)

Result: [1, 2, 3, 4, 5].

3. Swap dictionary keys and values – Use a dictionary comprehension.

dictionary = {"a": 1, "b": 2, "c": 3}
reversed_dictionary = {v: k for k, v in dictionary.items()}
print(reversed_dictionary)

Output: {1: 'a', 2: 'b', 3: 'c'}. Note that duplicate values keep the last key.

4. Generate a specific range of odd/even numbers – Use range with a step.

for n in range(10, 20, 2):
    print(n)

Output: 10 12 14 16 18.

5. Safely access a missing dictionary key – Prevent KeyError by using defaultdict or dict.get.

from collections import defaultdict
person_info = defaultdict(str)
person_info["name"] = "Maishu"
person_info["sex"] = "Male"
print(person_info["age"])  # Returns empty string instead of error
defaultdict

can be initialized with int, list, set, etc., to provide appropriate default values.

6. Locate the installation path of a Python module – Print the module object.

import requests
print(requests)

Typical output:

<module 'requests' from 'D:\\Python311\\Lib\\site-packages\\requests\\__init__.py'>

7. Extract all middle elements of a list – Use extended unpacking.

_, _, *elements, _, _ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print(elements)

Result: [3, 4, 5, 6, 7, 8, 9, 10].

8. Assign multiple variables from a list (or tuple) – Direct unpacking.

my_variables = [1, 2, 3, 4, 5]
a, b, c, d, e = my_variables
print(a, b, c, d, e)
# Output: 1 2 3 4 5

The same works with tuples:

my_variables = 1, 2, 3, 4, 5
print(type(my_variables))  # <class 'tuple'>
a, b, c, d, e = my_variables
print(a, b, c, d, e)

These eight concise tricks help Python developers write clearer, safer, and more efficient 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.

programming tipsdata-structurescode-snippets
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

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.