Fundamentals 10 min read

Hidden Python Tricks: Ternary Operator, enumerate, zip, List Comprehensions, Lambdas, Generators, Decorators and More

This article introduces a collection of lesser‑known Python techniques—including the ternary operator, enumerate, zip, list comprehensions, lambda functions, any/all, itertools, generators, decorators, dynamic imports, dictionary comprehensions, and mutable data structures—each explained with clear examples to help developers write more concise and efficient code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Hidden Python Tricks: Ternary Operator, enumerate, zip, List Comprehensions, Lambdas, Generators, Decorators and More

Python is a versatile language with many libraries and built‑in functions. This guide presents several hidden yet useful Python tricks that can make development faster and code more elegant.

1. Ternary Operator

The ternary operator provides a compact form of an if‑else statement:

value_if_true if condition else value_if_false

Example:

<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>

2. enumerate() Function

enumerate() adds a counter to an iterable and returns an enumerate object, useful for looping with index:

<code>fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
    print(index, fruit)
# 0 apple
# 1 banana
# 2 mango</code>

3. zip() Function

zip() aggregates elements from multiple iterables into tuples, enabling 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>

4. List Comprehension

List comprehensions create lists 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>

5. Lambda (Anonymous) Functions

Lambda functions define small, one‑off functions without the def keyword:

<code>add = lambda x, y: x + y
result = add(3, 4)
print(result)  # 7</code>

6. any() and all() Functions

any() returns True if any element of an iterable is true; all() returns True only if every element is true:

<code>numbers = [1, 2, 3, 0, 4]
print(any(numbers))   # True
print(all(numbers))   # False (0 makes it False)</code>

7. itertools Module

The itertools module offers tools for iterator manipulation, such as chain , product , and 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>

8. Generators

Generators produce values on‑the‑fly using the yield keyword, allowing efficient iteration without storing all items in memory:

<code># Using yield to create a generator
def fibonacci_series(n):
    a, b = 0, 1
    for i 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>

9. 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>

10. Variable‑Length Arguments (*args, **kwargs)

Use * to collect positional arguments and ** for 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>

11. Dynamic Import (importlib)

Import modules at runtime based on user input or configuration:

<code>import importlib
module_name = 'math'
module = importlib.import_module(module_name)
result = module.sqrt(9)
print(result)  # 3.0</code>

12. Dictionary Comprehension

Create dictionaries concisely from iterables:

<code>squared_numbers = {x: x**2 for x in range(1, 6)}
print(squared_numbers)
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}</code>

13. Callable Objects

Any object implementing __call__ can be invoked like a function:

<code>class Adder:
    def __call__(self, x, y):
        return x + y

adder = Adder()
result = adder(3, 4)
print(result)  # 7</code>

14. Underscores in Large Numbers

Use underscores to improve readability of large numeric literals:

<code>num_test = 100_345_405
print(num_test)  # 100345405</code>

15. Merging Dictionaries Quickly

Combine two dictionaries using the unpacking operator:

<code>dictionary_one = {"a": 1, "b": 2}
dictionary_two = {"c": 3, "d": 4}
merged = {**dictionary_one, **dictionary_two}
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}</code>

16. Mutability of Lists, Sets, and Dictionaries

Lists, sets, and dictionaries can be modified without changing their object IDs:

<code>cities = ["Munich", "Zurich", "London"]
print(id(cities))
cities.append("Berlin")
print(id(cities))  # same ID

my_set = {1, 2, 3}
print(id(my_set))
my_set.add(4)
print(id(my_set))  # same ID

thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print(id(thisdict))
thisdict["engine"] = "2500cc"
print(id(thisdict))  # same ID</code>

These hidden Python features can help you write cleaner, more efficient, and more Pythonic code.

Pythoncode examplesdecoratorsGeneratorsternary operatorlist comprehensionProgramming tricks
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.