I was trying to speed up some nested for loops with multiple internal loops in python 3.11:
for item1 in iterable1:
for item2 in interable2:
if condition == true:
expression1
for item3 in interable3:
if condition2 == true:
expression2
Note that the 2nd and 3rd for loops are at the same level and not nested, unlike This Question.
I learned that list comprehension and the map()
function is usually much faster than for
loops Here, and I'm trying to convert my nested loops into map()
function(s).
Can someone please explain how to construct such map()
functions and/or list comprehensions?
I thought I would do some research - there would surely be a answer for such a problem on the internet, but left empty handed. some resources used include:
I think you're confusing several concepts:
First, List comprehensions and for loops are the same thing. A list comprehension is merely a more compact way to write a for loop. You can rewrite any list comprehension as a for loop with no meaningful change in performance.
For example, if you start with the following for loop:
iterable1 = ["a", "b", "c", "a", "e", "f", "a"]
result = []
for item in iterable1:
if item == "a":
result.append(item + "FOO")
else:
result.append(item)
print(result)
# ['aFOO', 'b', 'c', 'aFOO', 'e', 'f', 'aFOO']
You can express this as a list comprehension as follows:
iterable1 = ["a", "b", "c", "a", "e", "f", "a"]
result = [item + "FOO" if item == "a" else item for item in iterable1]
print(result)
# ['aFOO', 'b', 'c', 'aFOO', 'e', 'f', 'aFOO']
The two examples above are exactly interchangeable - neither is superior to the other - they're just different ways of saying the same thing.
If you wanted to use map(), you could do it as follows:
iterable1 = ["a", "b", "c", "a", "e", "f", "a"]
conditional1 = lambda item: item == "a"
expression1 = lambda item: item + "FOO" if conditional1(item) else item
result = list(map(expression1, iterable1))
print(result)
# ['aFOO', 'b', 'c', 'aFOO', 'e', 'f', 'aFOO']
Using map() is meaningfully different from using a loop - but using a list comprehension is no different from using a loop.