5 Essential Python Tricks Every Programmer Should Know.

Ahmed Yasin
4 min readApr 24, 2023

Tips and Examples to Improve Your Python Code

Python is a versatile programming language that offers many features to help you write better and more efficient code. In this article, we will explore 7 essential Python tricks that every programmer should know, along with examples to illustrate their usefulness.

1 — List Comprehensions

List comprehensions are a concise and powerful way to create lists in Python. They allow you to create a list by applying an expression to each item in an iterable.

Example 1: Creating a list of squares from 1 to 10.

squares = [x**2 for x in range(1, 11)]
print(squares)

Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Example 2: Creating a list of even numbers from 1 to 20.

evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)

Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Example 3: Creating a list of uppercase letters from a string.

string = "Hello, World!"
uppercase = [char.upper() for char in string if char.isalpha()]
print(uppercase)

Output: ['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']

2 — Context Managers

Context managers are a useful tool for managing resources in Python. They allow you to allocate and release resources automatically, ensuring that they are properly cleaned up and not left dangling.

Example 1: Opening a file using a context manager.

with open('file.txt', 'r') as file:
for line in file:
print(line)

Example 2: Acquiring and releasing a lock using a context manager.

import threading

lock = threading.Lock()

with lock:
# do some thread-safe work

Example 3: Connecting to a database using a context manager.

import sqlite3

with sqlite3.connect('mydb.sqlite') as conn:
# do some database work

3 — Decorators

Decorators are a powerful tool for modifying the behavior of functions in Python. They allow you to add functionality to a function without modifying its source code.

Example 1: Measuring the execution time of a function using a decorator.

import time

def measure_time(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution time: {end - start:.3f} seconds")
return result
return wrapper

@measure_time
def my_function():
# do some work

Example 2: Logging the arguments and return value of a function using a decorator.

def log_function(func):
def wrapper(*args, **kwargs):
print(f"Function {func.__name__} called with args={args} kwargs={kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper

@log_function
def my_function(arg1, arg2):
# do some work
return result

Example 3: Caching the return value of a function using a decorator.

def cache_result(func):
cache = {}
def wrapper(*args):
if args in cache:
print(f"Using cached result for {args}")
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper

@cache_result
def expensive_function(arg1, arg2):
# do some work
return result

4 — Lambda Functions

Lambda functions are anonymous functions that you can define inline in your code. They are a convenient way to create small, one-off functions without cluttering up your code with unnecessary function definitions.

Example 1: Sorting a list of tuples by the second element.

my_list = [(1, 4), (2, 3), (3, 2), (4, 1)]
my_list.sort(key=lambda x: x[1])
print(my_list)

Output: [(4, 1), (3, 2), (2, 3), (1, 4)]

Example 2: Filtering a list of numbers to keep only the even ones.

my_list = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, my_list))
print(even_numbers)

Output: [2, 4, 6]

Example 3: Mapping a list of strings to their lengths.

my_list = ["foo", "bar", "baz"]
lengths = list(map(lambda x: len(x), my_list))
print(lengths)

Output: [3, 3, 3]

5 — Namedtuples

Namedtuples are a convenient way to create lightweight, immutable data structures in Python. They behave like tuples, but with named fields that make it easier to access their elements.

Example 1: Defining a namedtuple to represent a 2D point.

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p.x, p.y)

Output: 1 2

Example 2: Creating a list of namedtuples representing people.

from collections import namedtuple

Person = namedtuple("Person", ["name", "age"])
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 35),
]
for person in people:
print(f"{person.name} is {person.age} years old")

Output:

Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old

Example 3: Using a namedtuple as a return value from a function.

from collections import namedtuple

def divide(a, b):
Result = namedtuple("Result", ["quotient", "remainder"])
return Result(a // b, a % b)

result = divide(10, 3)
print(f"10 divided by 3 is {result.quotient} with a remainder of {result.remainder}")

Output: 10 divided by 3 is 3 with a remainder of 1.

In the End :

If you have any question you can ask in comments. If you like this must promote it.

Thanks for your time for reading my article.

--

--