Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Five Concise and Practical Python Techniques for Everyday Coding

Tech 1

List Comprehensions

List comprehensions offer a compact and readable way to construct sequences. Instead of initializing an empty list and appending elements in a loop, you express the entire transformation in a single line.

For example, generating squares of integers from 0 to 9:

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

Becomes:

squares = [num * num for num in range(10)]

The pattern generalizes across data types: [expression for item in iterable]. You can add filtering with if clauses:

even_squares = [n * n for n in range(10) if n % 2 == 0]
# [0, 4, 16, 36, 64]

Similar syntax applies to dictionary ({key: value for ...}), set ({expr for ...}), and generator expressions ((expr for ...)).

Anonymous Functions with lambda

lambda creates lightweight, inline functions without requiring a formal def statement. They’re ideal when a simple operation is needed once—especially as arguments to higher-order functions like sorted(), map(), or filter().

Consider sorting coordinate pairs by y-coordinate:

points = [(3, 7), (1, 2), (5, 4)]
points.sort(key=lambda p: p[1])
# [(1, 2), (5, 4), (3, 7)]

A lambda follows the form lambda parameters: expression. It implicitly returns the result of the expression:

multiply = lambda a, b: a * b
print(multiply(6, 7))  # 42

Enhanced Data Structures from collections

The collections module provides specialized container types that extend built-in behavior with improved utility and performance.

from collections import defaultdict, Counter, deque, namedtuple
  • defaultdict: Returns a default value (e.g., list, int, or a custom callable) when accessing a missing key, avoiding KeyError.
  • Counter: A subclass of dict optimized for counting hashable objects. Supports arithmetic operations and methods like most_common().
  • deque: A double-ended queue supporting O(1) appends and pops from both ends—ideal for queues, stacks, or sliding windows.
  • namedtuple: Creates immutable, tuple-like objects with named fields, improving code clarity and access via attribute names.

Example using namedtuple:

Person = namedtuple('Person', ['name', 'age', 'city'])
alice = Person('Alice', 30, 'Boston')
print(alice.name)  # Alice

Function Decorators

Decorators wrap a function to augment or modify its behavior without changing its source code. They follow the @decorator_name syntax above the function definition.

A timing decorator illustrates reusability:

import time

def benchmark(func):
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f'{func.__name__} ran in {elapsed:.4f}s')
        return result
    return wrapper

@benchmark
def compute_sum(n):
    return sum(i * i for i in range(n))

compute_sum(100_000)

This pattern enables cross-cutting concerns like logging, authentication, caching, or retry logic—all cleanly separated from core logic.

Unpacking and Zipping Iterables

The zip() function aggregates elements from multiple iterables into tuples. It stops at the shortest input, making it safe for parallel iteration:

firsts = ['Maya', 'Leo', 'Riley']
lasts = ['Chen', 'Martinez']

for first, last in zip(firsts, lasts):
    print(f'{first} {last}')
# Maya Chen
# Leo Martinez

zip() also supports unzipping when combined with the unpacking operator *. Given a list of records:

records = [('Zoe', 28, 'Engineer'), ('Sam', 35, 'Designer')]
names, ages, roles = zip(*records)
print(names)  # ('Zoe', 'Sam')

This avoids manual indexing and enhances readability when extracting columns from tabular data.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.