5 tips for writing loops more efficiently in Python

Mondo Technology Updated on 2024-01-30

If possible, try to avoid loops and use built-in function methods instead. For example, when we calculate the sum of the list elements, we can use sum().

Use loops to sum the list. 

numbers = [1, 2, 3, 4, 5, 6]

result = 0

for num in numbers:

result += num

print(result)

Use sum() to sum the list.

result = sum(numbers)

print(result)

When you need to iterate over a list, and you need to use both indexes and elements, use the built-in function instead: enumerate().

Use range().

data = ["a", "b", "c"]

for i in range(len(data)):

print(i, data[i])

Use enumerate().

for idx, val in enumerate(data):

print(idx, val)

When traversing multiple lists, use zip(), which returns a tuple iterator.

Use range().

a = [1, 2, 3]

b = ["a", "b", "c"]

for i in range(len(a)):

print(a[i], b[i])

Use zip().

for val1, val2 in zip(a, b):

print(val1, val2)

Use list inferences or generator expressions to simplify, make them appear more concise, and run faster.

lst = 

for i in range(1, 10):

if i % 2 == 0:

lst.append(i**2)

print(lst)

Use list inferences.

lst = [ i**2 for i in range(1, 10) if i % 2 == 0]

print(lst)

fruit = [("apple", 5), "banana", 10), "apple", 20)]

sum1 = 0

for i in fruit:

if i[0] == "apple":

sum1 += i[1]

print(sum1)

Use generator expressions.

sum_item = (i[1] for i in fruit if i[0] == "apple")

sum1 = sum(sum_item)

print(sum1)

The IterTools module provides functions for creating iterators for efficient loops. Let's take a look at three of these functions: islice(), pairwise(), takewhile().

Creates an iterator that returns the specified element from the iterable object.

lst = ["1", "2", "3", "4", "5", "6"]

for i, j in enumerate(lst):

if i >= 3:

breakprint(j)

from itertools import islice

lst2 = islice(lst, 3)

for i in lst2 :

print(i)

A pair of samples is returned at a time.

from itertools import pairwise

data = 'abcde'

for i in range(len(data)-1):

print(data[i], data[i+1])

for pair in pairwise('abcde'):

print(pair[0], pair[1])

Iterable objects are retrieved and included in the generator object when the current item satisfies the criteria.

for item in [1, 2, 4, -1, 4, 1]:

if item >= 0:

print(item)

else:break

from itertools import takewhile

items = takewhile(lambda x: x >= 0, [1, 2, 4, -1, 4, 1])

for item in items:

print(item)

It's not easy to create an article, if you like this article, please follow, like and share it with your friends. If you have comments and suggestions, please give us feedback in the comments.

Related Pages