Lesser‑Known Python Tricks and Techniques
This article introduces several lesser‑known Python tricks—including the ternary operator, enumerate, zip, list comprehensions, lambda functions, any/all, itertools, generators, decorators, and the use of * and ** for multiple arguments—each explained with concise examples to help developers write cleaner, more efficient code.
Python is a versatile language with many built‑in functions and idioms that can make code shorter and more readable. The following examples demonstrate a collection of lesser‑known tricks useful for everyday development.
Ternary Operator
The ternary operator provides a one‑line conditional expression: value_if_true if condition else value_if_false .
<code>a = 5
b = 10
max = a if a > b else b # value_if_true if condition else value_if_false
print(max) # 10</code>enumerate() Function
enumerate() adds a counter to an iterable and returns an enumerate object, useful for tracking indices while iterating.
<code>fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple
# 1 banana
# 2 mango</code>zip() Function
zip() aggregates elements from multiple iterables into tuples, allowing parallel iteration.
<code>list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for x, y in zip(list1, list2):
print(x, y)
# 1 a
# 2 b
# 3 c</code>List Comprehension
List comprehensions create new lists from existing iterables in a single, readable line.
<code>squared_numbers = [x**2 for x in range(1, 6)]
print(squared_numbers) # [1, 4, 9, 16, 25]</code>Lambda (Anonymous) Functions
Lambda expressions define small, unnamed functions on the fly.
<code>add = lambda x, y: x + y
result = add(3, 4)
print(result) # 7</code>any() and all() Functions
any() returns True if at least one element of an iterable is truthy; all() returns True only if every element is truthy.
<code>numbers = [1, 2, 3, 0, 4]
print(any(numbers)) # True
print(all(numbers)) # False (because of 0)</code>itertools Module
The itertools module supplies tools for efficient iteration, such as permutations .
<code>import itertools
numbers = [1, 2, 3]
result = list(itertools.permutations(numbers))
print(result)
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]</code>Generators
Generators produce values lazily using the yield keyword, allowing creation of custom iterators without storing all items in memory.
<code>def fibonacci_series(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for number in fibonacci_series(10):
print(number)
# 0 1 1 2 3 5 8 13 21 34</code>Decorators
Decorators modify the behavior of functions or classes using the @ syntax.
<code>def log_function(func):
def wrapper(*args, **kwargs):
print(f'Running {func.__name__}')
result = func(*args, **kwargs)
print(f'{func.__name__} returned {result}')
return result
return wrapper
@log_function
def add(x, y):
return x + y
print(add(5, 7))
# Running add
# add returned 12
# 12</code>Handling Multiple Function Arguments (* and **)
The *args and **kwargs syntax allows functions to accept an arbitrary number of positional and keyword arguments.
<code>def print_arguments(*args, **kwargs):
print(args)
print(kwargs)
print_arguments(1, 2, 3, name='John', age=30)
# (1, 2, 3)
# {'name': 'John', 'age': 30}</code>These techniques collectively help Python developers write more concise, readable, and efficient code.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.