10 Mind-Blowing Python Tricks You Never Knew
1.List Comprehension: A concise and efficient way to create a new list from existing iterable objects.
Example: # create a list of squares of numbers 1 to 10
squared_numbers = [x**2 for x in range(1, 11)]
print(squared_numbers)
2.Generators and Yield: Generators are a special type of function that can be used to create iterators. Yield statement is used to return values from the generator.
Example: # a generator function to generate Fibonacci series
def fibonacci(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
fib = fibonacci(10)
for i in fib:
print(i)
3.Context Managers: Used to manage resources such as file handles, sockets, and database connections.
Example: # using context managers to open and read a file
with open(‘file.txt’, ‘r’) as f:
content = f.read()
print(content)
4.Decorators: A powerful mechanism to modify or extend the behavior of functions or classes.
Example: # A simple example of a decorator
def decorator_example(func):
def wrapper(*args, *kwargs): print(“Something is happening before the function is called.”) func(args, **kwargs)
print(“Something is happening after the function is called.”)
return wrapper
@decorator_example
def say_hello():
print(“Hello!”)
say_hello()
#Output: #Something is happening before the function is called. #Hello! #Something is happening after the function is called.5.Metaclasses: A class that defines the behavior of other classes.
Example: # a simple example of a metaclass
class Meta(type):
def init(cls, name, bases, attrs):
attrs[‘new_attribute’] = ‘new_value’
super().init(name, bases, attrs)
class MyClass(metaclass=Meta):
pass
obj = MyClass()
print(obj.new_attribute)
6.Enumerate and Zip: Enumerate allows you to loop over a list and get both the index and value of each item. Zip allows you to loop over multiple lists at the same time.
Example: # using enumerate
fruits = [‘apple’, ‘banana’, ‘cherry’]
for i, fruit in enumerate(fruits):
print(i, fruit)
fruits = [‘apple’, ‘banana’]
prices = [1, 2]
for fruit, price in zip(fruits, prices):
print(fruit, price)
7.Dynamic Importing: The ability to import a module dynamically at runtime.
Example: # dynamically importing a module
module_name = ‘math’
module = import(module_name)
print(module.sqrt(16))
8.Multiple Function Arguments: The ability to accept a variable number of arguments for a function.
Example: # a function to accept any number of arguments
def print_arguments(*args, **kwargs):
print(args)
print(kwargs)
9.Ternary Operators: A shorthand for writing simple if-else statements.
The syntax is:value_if_true if condition else value_if_false
Example:
x = 10
y = 20
max_value = x if x > y else y
print(max_value) # Output: 20
- Property Decorators: A decorator that allows you to define properties in a class that can be accessed like attributes.
Example:
class Person:
def init(self, name):
self._name = name @property
def name(self):
return self._name @name.setter
def name(self, value):
if not isinstance(value, str):
raise ValueError(“Name must be a string.”)
self._name = value @name.deleter
def name(self):
del self._name
person = Person(“John”)
print(person.name) # Output: John
person.name = “Jane”
print(person.name) # Output: Jane
del person.name
print(person.name) # Raises an AttributeError
In the above example, name is a property of the Person class. The @property decorator defines the getter method, the @name.setter decorator defines the setter method, and the @name.deleter decorator defines the deleter method. This allows you to control how the name attribute is accessed and modified.