Photo by Glenn Carstens-Peters on Unsplash
Replace Loops with These Incredible Tricks!
Do More with Less Code in Python!
Introduction
As a beginner in Python programming, you might have already encountered loops in your code. Loops are important for repeating tasks, but sometimes, they can make the code look lengthy and complex. What if I told you that there are simpler and more concise ways to achieve the same results?
In this beginner's guide, we'll introduce you to Python's secret weapons: list comprehensions and functional tools like map()
, filter()
, and reduce()
. These tools should be in your Python toolbox to make your code shorter, cleaner and more readable.
List Comprehensions
List Comprehension is a very concise and readable way to create lists in Python. It allows us to create new lists by applying an expression on each item
in an iterable (e.g., lists, tuples, range).
Syntax:
new_list = [expression for item in iterable if condition]
Where:
expression: An expression to be applied to each item.
item: A variable representing each item in iterable.
iterable: The iterable from which a new list is created.
condition(optional): A condition used to filter the items.
Example:
Imagine you have a list of numbers, and you want to create a new list containing the squares of even numbers from the original list.
- Using for loop
# Using a for loop
numbers = [1, 2, 3, 4, 5, 6]
squares_of_evens = []
for n in numbers:
if n % 2 == 0:
squares_of_evens.append(n ** 2)
print(squares_of_evens)
- Using List Comprehension
# Using List Comprehensions
numbers = [1, 2, 3, 4, 5, 6]
squares_of_evens = [n ** 2 for n in numbers if n % 2 == 0]
print(squares_of_evens)
If you observe carefully, the second approach does the same task but is easy to read, write and understand.
Lambda Expressions
Lambda Expressions, also known as lambda functions, provide a way to write small and anonymous functions
. They are mainly used when we want to pass a function as an argument to higher-order functions like map(), filter() etc.
Syntax:
lambda arguments: expression
Where:
arguments: The arguments we wish to pass the function.
expression: The operations to be applied.
Example:
Suppose you have a list of numbers and you want to sort them in ascending order based on their remainder when divided by 5.
- Using standard method
numbers = [15, 3, 8, 12, 7]
# Using regular functions
def remainder_mod5(x):
return x % 5
sorted_numbers = sorted(numbers, key = remainder_mod5)
print(sorted_numbers)
- Using lambda expression
numbers = [15, 3, 8, 12, 7]
# Passing lambda expression instead of a regular function
sorted_numbers = sorted(numbers, key = lambda x: x % 5)
print(sorted_numbers)
The above example proves that lambda functions are best for creating short and one-time-used functions improving the readability of the code.
Map Function
The map() function is a built-in function
in Python that is used to apply a function to every item in an iterable
(list, tuple or other iterable). It returns a map object
containing the result. It is an excellent alternative for explicit "for loops".
Syntax:
map(function, iterable)
Where:
function: A function to apply on every item in the iterable.
iterable: An iterable containing elements.
Example:
Let's say you have a list of numbers, and you want to square each number.
- Using loops
# Using for loop
numbers = list(range(1, 11))
for i in range(len(numbers)):
numbers[i] = numbers[i] ** 2
print(numbers)
- Using map() function
numbers = list(range(1, 11))
# Function to perform squaring of elements
square = lambda x: x ** 2
# map() function to apply function to all elements
result = map(square, numbers)
print(list(result))
Filter Function
The filter()
function is a built-in function
in Python that allows us to filter items from an iterable based on a specific condition
. It returns an iterable
(a filter object) which contains the result. It provides a convenient way to filter the elements without using loops.
Syntax:
filter(function, iterable)
Where:
function: A function that defines the condition for filtering.
iterable: An iterable containing items to be filtered.
Example:
Let's say you have a list of numbers, and you want to filter out the even numbers.
- Using loops
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers)
- Using filter() function
# Function to filter even numbers
def filter_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
# Passing the function and iterable in filter function
result = filter(filter_even, numbers)
# Printing the result as list since filter returns a filter object
print(list(result))
Reduce Function
The reduce() function is a part of the functools
module in Python. It takes a binary function
(a function that takes two arguments) and an iterable and applies that binary function to every element
of the iterable, thus reducing it to a single value.
Syntax:
functools.reduce(function, iterable)
Where:
function: A binary function that takes two arguments and returns a single result.
iterable: An iterable containing elements to be reduced.
Example:
Let's say you have a list of numbers, and you want to find the product of all the numbers.
- Using loops
numbers = [1, 2, 3, 4, 5]
product = 1
for num in numbers:
product *= num
print(product)
- Using reduce() function
from functools import reduce
# Function to multiple two numbers
def multiply(x, y):
return x * y
numbers = [1, 2, 3, 4, 5]
# Applying reduce function and storing the result
product = reduce(multiply, numbers)
print(product)
Some Best Practices
- List Comprehensions
Use meaningful variable names
that convey the purpose of the list comprehension. This enhances the code readability.
# Good Practice
squared_numbers = [num ** 2 for num in numbers]
# Bad Practice
sqr = [i ** 2 for i in numbers]
- map()
map() function is an excellent choice for performing transformation to every element
in an iterable.
result = map(square, number)
- Lambda Functions
Lambda functions are the best choice when we want to keep the code concise.
result = map(lambda num: num * 2, numbers)
- filter()
filter() is useful for selecting elements based on a given condition.
# Filters even numbers
result = filter(is_even, numbers)
- reduce()
reduce() function is an ideal choice for performing cumulative operations
like sum, product etc.
product = functools.reduce(multiply, numbers)
Check Your Understanding
What is the primary purpose of list comprehension in Python?
a) To create a new list from an existing one
b) To execute complex conditional statements
c) To define functions for data transformation
d) To perform cumulative operations on data
Which of the following functions is used to apply a specified function to every element in an iterable?
a) list()
b) apply()
c) map()
d) transform()
When should you consider using a lambda
function with map()
?
a) For all transformations
b) Only for simple transformations
c) Only for complex transformations
d) Never use lambda
functions with map()
Remember to drop your answers in the comments below! We're curious to see how many you got right. It's like a mini Python coding quiz.
Check out my most viewed articles on Fake Data Generation and Sketchy Visuals.
Connect with me on LinkedIn.
Subscribe to my newsletter and get such hidden gems straight into your inbox! Happy Data Exploring ^_^