Python Programming
Coding Tips
Programming Languages
Advanced Features
Python Techniques

Hidden features of Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Python, a versatile and widely-used programming language, is renowned for its simplicity and readability, making it accessible for beginners yet powerful enough for seasoned developers. Beyond its well-known features, Python has several hidden or lesser-known functionalities that can significantly boost productivity and simplify many programming tasks. This article uncovers some of these hidden gems, providing technical explanations and examples to help you harness their potential.

1. Slicing with Extended Unpacking

In Python, extended unpacking can be used to elegantly handle lists or tuples. This feature, introduced in Python 3, extends the basic unpacking to allow for a catch-all * operator that can be used to grab excess items.

python
1a, *b, c = [1, 2, 3, 4, 5]
2print(a)  # 1
3print(b)  # [2, 3, 4]
4print(c)  # 5

This technique is incredibly useful in scenarios where you need to partition data into several parts or when you need the first and last element separately while performing operations on the remaining list.

2. f-string Debugging

The f-strings introduced in Python 3.6 not only made formatting easier but also provide a handy debugging tool. By adding = to an expression within an f-string, you can print both the expression and its value, which is a boon for debugging.

python
1x = 10
2y = 5
3print(f"{x+y=}, {x*y=}")
4# Output: x+y=15, x*y=50

3. Caching with functools.lru_cache

Python's functools module offers a powerful decorator, lru_cache, that caches the results of a function depending on the arguments it is given. This feature is incredibly useful for optimizing performance, especially in recursive functions or functions that are called frequently with the same parameters.

python
1from functools import lru_cache
2
3@lru_cache(maxsize=32)
4def fib(n):
5    if n < 2:
6        return n
7    return fib(n-1) + fib(n-2)
8
9print(fib(10))  # 55, subsequent calls with the same argument are instant

4. The Walrus Operator

The Walrus operator (:=) introduced in Python 3.8, also known as the assignment expression operator, lets you assign values to variables as part of an expression.

python
if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

This feature simplifies code and can reduce the number of lines, especially when handling complex expressions.

5. The Power of collections

The collections module has several powerful and efficient container datatypes. One such example is defaultdict, which provides default values for missing keys, saving you the hassle of checking for existence and initializing.

python
1from collections import defaultdict
2
3counter = defaultdict(int)
4for char in "hello world":
5    counter[char] += 1

6. Generator Expressions for Memory Efficiency

Python supports using generator expressions to create generators (lazy iterators) rather than fully initializing the elements in memory like list comprehensions.

python
# Sum squares of even numbers from 1 to 10
total = sum(i * i for i in range(11) if i % 2 == 0)

This is especially useful when working with large datasets or streams of data where memory management is critical.

Summary Table

FeatureBenefitExample Usage
Extended UnpackingSimplifies data partitioning and assignmenta, *b, c = range(5)
f-string DebuggingSimplifies debugging with direct expression outputprint(f"&#123;x=&#125;")
functools.lru_cacheOptimizes performance through caching@lru_cache decorator on function
Walrus OperatorReduces code redundancyif (n := len(a)) > 10
collections moduleProvides efficient container datatypesdefaultdict, Counter
Generator ExpressionsSaves memory by lazily loading data(x*x for x in range(10))

Employing these hidden features can dramatically optimize the efficiency, readability, and maintainability of Python code. While these features are powerful, it's also essential to understand when and where their application can bring about the greatest benefit, tailoring their use to the demands and context of your specific projects.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.