25 Essential Python Tricks Every Developer Should Know
This article compiles a curated list of practical Python tricks—from chained comparisons and enumerate usage to generators, dictionary comprehensions, decorators, and context managers—providing clear examples and explanations that help developers write more concise, efficient, and readable code.
Chained Comparisons
Python allows multiple comparisons to be chained; the interpreter evaluates them as a series of logical and operations. Example:
>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
TrueThis makes range checks more readable and is uncommon in many other languages.
Enumerate
The built‑in enumerate wraps any iterable and yields (index, item) pairs, eliminating the need for manual index handling with range(len(...)). Example:
>> a = ['a', 'b', 'c', 'd', 'e']
>>> for index, item in enumerate(a):
... print(index, item)
0 a
1 b
2 c
3 d
4 e enumerateaccepts an optional start argument to set the initial index.
Generator Expressions
Generator expressions create generator objects that produce items lazily, saving memory compared to list comprehensions. Example:
>> x = (n for n in foo if bar(n))
>>> type(x)
<class 'generator'>
>>> for n in x:
... passGenerators are slower for small data but excel with large or infinite sequences because values are computed on demand and cannot be rewound.
Dictionary Comprehensions
From Python 2.7/3.0 onward, dictionary comprehensions provide concise syntax for building dictionaries from iterables:
>> d = {key: value for (key, value) in iterable}
>>> d = {value: foo(value) for value in sequence if bar(value)}They can be combined with nested generators or conditional logic.
iter() with Callable and Sentinel
The built‑in iter can be called with a callable and a sentinel value. It repeatedly invokes the callable until the returned value equals the sentinel:
def seek_next_line(f):
for c in iter(lambda: f.read(1), '
'):
passMutable Default Arguments
Using a mutable object as a default parameter value causes the same object to be shared across calls. Replace it with None and create a new object inside the function:
>> def foo(x=None):
... if x is None:
... x = []
... x.append(1)
... print(x)
>>> foo()
[1]
>>> foo()
[1]Sending Values to Generators
Generators can receive values via the send() method, allowing external code to modify the generator’s internal state:
def mygen():
a = 5
while True:
f = (yield a)
if f is not None:
a = f
g = mygen()
g.next() # 5
g.send(7) # 7
g.next() # 7Future Import Braces Joke
Importing braces from __future__ always raises a SyntaxError, illustrating that Python will never adopt C‑style curly‑brace syntax.
Slice Step Parameter
Slice notation supports a step argument, enabling selections like every second element or reversing a sequence:
>> a = [1, 2, 3, 4, 5]
>>> a[::2]
[1, 3, 5]
>>> a[::-1]
[5, 4, 3, 2, 1]Built‑in functions list.reverse() (in‑place) and reversed() (returns an iterator) provide additional reversal options.
Decorators
Decorators wrap functions to add behavior such as logging arguments. The @decorator syntax is syntactic sugar for manually assigning the wrapper:
def print_args(func):
def wrapper(*args, **kwargs):
print('Arguments:', args, kwargs)
return func(*args, **kwargs)
return wrapper
@print_args
def write(text):
print(text)
write('foo')
# Output:
# Arguments: ('foo',) {}
# foofor…else Syntax
The else block after a for loop runs only if the loop completes without encountering break. It can be rewritten with a flag variable for clarity.
__missing__ Method (Python 2.5)
Defining __missing__(self, key) in a dict subclass provides a fallback for missing keys, similar to defaultdict but with custom logic.
class MyDict(dict):
def __missing__(self, key):
self[key] = rv = []
return rv
m = MyDict()
m['foo'].append(1)
m['foo'].append(2)
print(dict(m)) # {'foo': [1, 2]}Variable Swapping
Python supports tuple unpacking for simultaneous assignment, enabling concise swaps:
>> a, b = 10, 5
>>> a, b = b, a
>>> a, b
(5, 10)Readable Regular Expressions
Using the re.VERBOSE flag, regular expressions can be split across lines and include comments for clarity.
Function Argument Unpacking
The * and ** operators unpack sequences and mappings when calling functions, simplifying argument passing:
def draw_point(x, y):
pass
point = (3, 4)
draw_point(*point)
kwargs = {'x': 2, 'y': 3}
draw_point(**kwargs)Dynamic Type Creation
The type function can create new classes at runtime:
>> NewType = type('NewType', (object,), {'x': 'hello'})
>>> n = NewType()
>>> n.x
'hello'Context Managers and with Statement
Objects implementing __enter__ and __exit__ can be used with with to ensure proper resource handling, such as automatically closing files:
with open('foo.txt', 'w') as f:
f.write('hello!')dict.get() and setdefault()
The get() method returns None (or a default) for missing keys, while setdefault() inserts a key with a default value if it does not exist.
collections.Counter
Counteris a dict subclass for counting hashable objects:
from collections import Counter
cnt = Counter('helloworld')
print(cnt) # Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})
print(cnt['l']) # 3Descriptors
Descriptors define __get__, __set__, and __delete__ methods to control attribute access, forming a core part of Python’s data model.
Conditional Assignment
Python’s ternary conditional expression x = a if condition else b replaces the C‑style ?: operator, offering clearer readability.
Exception else Clause
An else block after try/except runs only when no exception occurs, providing a place for code that should execute after a successful try but before finally.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
