SoFunction
Updated on 2025-03-01

15 advanced Python tips to improve code efficiency and more Pythonic

Simplify code using list comprehension

List comprehensions provide a concise and elegant approach. They can often replace traditional loops and conditional statements, making the code more concise and readable. However, it is not recommended to write the list comprehension here too complicated. After all, the code is written for people to read, and then it is read by the machine.

# Ordinary writingnumbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
    squared_numbers.append(num ** 2)
# Use list comprehensionsquared_numbers = [num ** 2 for num in numbers]

Improve memory efficiency with generator expressions

Similar to list comprehensions, generator expressions allow you to create iterators in a concise way. The main difference is that generator expressions do not store the entire sequence in memory, thus saving more memory.

Create a generator expression using brackets instead of square brackets:

# List comprehensionsquared_numbers = [num ** 2 for num in numbers]
# Generator expressionsquared_numbers = (num ** 2 for num in numbers)

Learn to use the enumerate() function

When it is necessary to traverse an iterable element and plan to use the index of each element,enumerate()Functions come in handy. It returns a tuple iterator containing the index and the corresponding elements. Here is an example:

# List comprehensionsquared_numbers = [num ** 2 for num in numbers]
# Generator expressionsquared_numbers = (num ** 2 for num in numbers)

Use join() to simplify string concatenation

use+Operators can be inefficient in concatenating strings, especially when dealing with large strings or multiple string concatenation. On the contrary, using the join() method can efficiently concatenate multiple strings. I personally use this method often, and when using lists to splice strings, the writing will be more flexible:

fruits = ['apple', 'banana', 'cherry']
combined_fruits = ', '.join(fruits)
print(combined_fruits)  
# Output: apple, banana, cherry

Use the zip() function to perform parallel iteration

passzip()Functions can traverse multiple traversable numbers in parallel. It takes multiple iterations as input and returns an iterator that produces tuples containing elements from each iteration. Here is an example:

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 32, 40]
for name, age in zip(names, ages):
    print(f"Name: {name}, Age: {age}")

Use Simplified Dictionary Defaults

collectionsThe module provides a name calleddefaultdictThe convenience class is built-indictSubclasses of class. If the key value does not exist, it automatically specifies a default value for it, eliminating explicit checking. Here is an example:

from collections import defaultdict
fruit_counts = defaultdict(int)
fruits = ['apple', 'banana', 'cherry', 'banana']
for fruit in fruits:
    fruit_counts[fruit] += 1
print(fruit_counts)  
# Output: {'apple': 1, 'banana': 2, 'cherry': 1}

Use any() and all() functions cleverly

any() andall()Functions are very useful when dealing with iterable data structures. If at least one element in the iterable data structure isTrue,butany()Function returnsTrue,andall()Functions are only in all elementsTrueReturn onlyTrue. Here is an example:

numbers = [1, 2, 3, 4, 5]
print(any(num > 3 for num in numbers))  
# Output: True
print(all(num > 3 for num in numbers))  
# Output: False

Count elements using

Classes provide a convenient way to count elements in an iterable representative. It returns a dictionary-like object where the element is a key and the count is a value. Here is an example:

from collections import Counter
fruits = ['apple', 'banana', 'cherry', 'banana']
fruit_counts = Counter(fruits)
print(fruit_counts)  
# Output: Counter({'banana': 2, 'apple': 1, 'cherry': 1})

Decorate functions with @staticmethod and @classmethod

@staticmethodThe decorator allows you to define static methods in the class. These methods cannot access the instance or the class itself, but can be called without instantiating the object. same,@classmethodThe first parameter of the method defined by the decorator is the class itself, not the instance. Here is an example:

class MathUtils:
    @staticmethod
    def square(x):
        return x ** 2
    @classmethod
    def cube(cls, x):
        return x ** 3
print((3))  # Output: 9
print((3))  # Output: 27

Use slots to reduce memory usage

Python stores instance properties in a dictionary by default, which consumes a lot of memory, especially when creating many instances. However, you can use the slots property to tell Python to allocate memory for a fixed set of instance variables, thereby reducing memory usage. Here is an example:

class Point:
    __slots__ = ['x', 'y']
    def __init__(self, x, y):
         = x
         = y

This limits the attributes onlyxandy, if you try to bind other attributes, it will be reportedAttributeErrormistake.

Use Ignore exceptions

The context manager can conveniently ignore specific exceptions that appear in the code block. It helps avoid unnecessarytry-exceptCode blocks and keep the code neat. Here is an example:

from contextlib import suppress
with suppress(FileNotFoundError):
    with open('', 'r') as file:
        contents = ()

The above are 15 advanced Python techniques to improve code efficiency and make it more Pythonic. For more information about Python Pythonic efficient code, please follow my other related articles!