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.
1. Use underscores to separate large numbers – Improves human readability of big integers. Example:
num = 1000000000Formatted versions:
num1 = 1_000_000_000 # Western style num2 = 10_0000_0000 # Chinese styleBoth 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
4To 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 errordefaultdict 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 5The 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.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.