Eliminating Loop from Python Code
In Python programming language, To increase our overall performance of applications there are several ways to eliminate loops in Python or replace loops from our Python code with various methods and strategies. It will enhance the performance and readability of the Python code.
- Using List Comprehension
- Using Itertools
- Using Pandas
- Using Generator Expression
Eliminate Loops with List Comprehension
A List comprehensions are another way to generate lists without the need for explicit loop structures. They are more efficient than traditional loops and improve code readability.
Python3
# Without list comprehension square1 = [] for i in range ( 8 ): square1.append(i * * 2 ) # With list comprehension square2 = [i * * 2 for i in range ( 8 )] print ( "Using Loop: " , square1) print ( "Using List Comprehension: " , square2) |
Output:
Using Loop: [0, 1, 4, 9, 16, 25, 36, 49]
Using List Comprehension: [0, 1, 4, 9, 16, 25, 36, 49]
Eliminate Loops with Itertools
The Python itertools modules are a collection of tools for handling iterators. They can eliminate the need for complex loops and make code more efficient and cleaner.
Python3
import itertools # Flattening a list of lists using a loop lists = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] flattened = [] for sublist in lists: for item in sublist: flattened.append(item) print (flattened) # Flattening a list of lists using itertools flattened = list (itertools.chain( * lists)) print (flattened) |
Output:
Using loop: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Using itertools: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Remove Loops with Python Package – Pandas
You can eliminate loops while working with numerical data, and libraries in Python such as NumPy and Pandas. These Libraries leverage a technique called Vectorization. It generally performs operations on the entire array of data.
Let’s consider a simple example in which we need to square each number in a list and the range is given from 1 to 6.
Example: By using a for loop
Python3
numbers = list ( range ( 1 , 6 )) squares = [] for number in numbers: squares.append(number * * 2 ) print (squares) |
Output:
Using loop: [1,4,9,16,25]
Example: By using NumPy
Python3
import numpy as np numbers = np.arange( 1 , 6 ) squares = numbers * * 2 print (squares) |
Output:
Using NumPy: [1 4 9 16 25]
Eliminate Loops with Built-in Functions: map(), reduce, and filter()
Python’s built-in function “map()“, “reduce()“, and “filter()” provides powerful, functional programming alternatives to loops.
“map()”: It applies a function to all items in an input list.
Python3
numbers = list ( range ( 1 , 6 )) squares = list ( map ( lambda x: x * * 2 , numbers)) print (squares) |
Output:
Using map(): [1,4,9,16,25]
“reduce()”: It applies a function of two arguments cumulatively to the elements of an iterable.
Python3
from functools import reduce numbers = list ( range ( 1 , 6 )) product = reduce ( lambda x,y: x * y, numbers) print (product) |
Output:
Using reduce(): 120
“filter()”: It creates a list of elements for which the function returns True.
Python3
numbers = list ( range ( 1 , 6 )) even_numbers = list ( filter ( lambda x: x % 2 = = 0 , numbers)) print (even_numbers) |
Output:
Using Filter(): [2, 4]
Remove Loops with Generator Expression
The Generators are a main type of Python function that allows you to create an iterable object, but they generate the value according to the need, which can save memory while dealing with large data sets.
Python3
# Using a for loop to create a list of squares squares = [] for n in range ( 50000 ): squares.append(n * * 2 ) print (squares) # Using a generator expression # Reduced to 10 for brevity squares_gen = (n * * 2 for n in range ( 50000 )) for square in squares_gen: print (square, end = ' ' ) |
Output:
Using for loop: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600,…]
Using generator expression: 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600………
Eliminating Loop from Python Code
In general, Loops are a pillar of any programming language. Loops allow us to execute a set of statements multiple times, which is particularly useful when dealing with lists, arrays, and kind of any of iterable. However, loops especially nested loops can slow down your code and affect the overall performance of your application.
Contact Us