5 Advanced Python Tricks That Will Make You A True Coding Master

When I first started programming in Python, I was amazed by the simplicity and elegance of the language. But over time, I discovered that Python hides much more than meets the eye. There are many small but very powerful tricks that can make a programmer's life much easier and make the code not only more concise but also more efficient.

Today I want to share with you five such tricks that will take your skills to the next level. Let's go!

1. Lambda functions: compact and convenient

I love lambda functions for their brevity. They are perfect when you want to write a small function right in the line of code and not clutter the namespace with unnecessary definitions.

For example, this is what a typical function for multiplying two numbers looks like:

def multiply(x, y):
    return x * y

And here's the same thing, only with lambda:

multiply = lambda x, y: x * y

Why use lambda functions? They are great when you need to pass a simple function inside another function. Here is an example of sorting a list of dictionaries by age:

people = [{'name': 'Алиса', 'age': 30}, {'name': 'Боб', 'age': 25}, {'name': 'Чарли', 'age': 35}]

# Сортируем по возрасту
sorted_people = sorted(people, key=lambda person: person['age'])

print(sorted_people)

When I need to do something quickly on the fly, lambda always saves the day. The code looks cleaner, and I don't have to create a separate function if it's only used once.

2. Generators: Working with Big Data Without Extra Load

Generators are a godsend when you need to process large amounts of data. Especially if the data comes in gradually, and loading it all into memory just doesn't make sense.

When I work with large files, instead of reading the entire file at once, I use a generator to process it line by line. This not only saves memory, but also allows me to work with the data more efficiently.

Here is an example of how you can read a huge file line by line:

def read_large_file(file_path):
    with open(file_path) as file:
        for line in file:
            yield line.strip()  # Используем yield, чтобы возвращать строки по одной

# Используем генератор
for line in read_large_file('huge_file.txt'):
    print(line)

When a file weighs several gigabytes, this is a lifesaver. Since the lines are not loaded all at once, but are generated as needed, memory is used very carefully.

3. Decorators: adding functionality without touching the code

Decorators are one of those tools I underestimated when I first started learning Python. Now I use them all the time when I need to add repetitive logic to functions without changing the function itself.

For example, I often want to see how long a function takes to execute. Instead of manually building the time measurement into each function, I can create a decorator:

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Функция {func.__name__} выполнилась за {end_time - start_time:.4f} секунд")
        return result
    return wrapper

Now I can simply add this decorator to any function:

@timer
def slow_function():
    time.sleep(2)
    print("Функция завершена")

slow_function()

I run a function and immediately see how much time it took. This is very convenient, especially when optimizing code.

4. Using collections for more convenient data structures

When I need something more complex than simple lists or dictionaries, I often use the module collections. This is an amazing library that provides more powerful and flexible data structures.

For example, defaultdict — is a dictionary with a preset default value. I once had a task to count how many times each word appeared in a text. In a standard dictionary, this would require checking if the key already existed, and if not, adding it. And with defaultdict it's done easier:

from collections import defaultdict

text = "это пример текста, это всего лишь пример"
word_count = defaultdict(int)

for word in text.split():
    word_count[word] += 1

print(word_count)

Every time a new word is encountered, it is automatically added to the dictionary with an initial value of 0, and then simply incremented by 1. This simplifies the code a lot, and I don't have to worry about checking.

5. List Compositions: Write Less, Do More

Finally, list comprehensions are my favorite. They allow you to write entire loops on one line, and at the same time make your code more readable.

Here's an example where I need to create a list of squares of all numbers from 0 to 9:

squares = [x**2 for x in range(10)]
print(squares)

Without list comprehensions, we would have to write more cumbersome code:

squares = []
for x in range(10):
    squares.append(x**2)

It seems like a small change, but when you see these constructs often, you really start to appreciate Python's brevity.

Conclusion

These tricks have become real helpers for me in my daily work. There is nothing super complicated in them, but each of them can significantly simplify the life of a programmer. Try to implement them in your code, and you will immediately feel the difference.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *