I came across a few articles and StackOverflow discussions where it is usually recommended to use list comprehension while dealing with lists.
I usually come across a common loop structure where I have a list and I have to process it and store the results in a new list.
So something like (For the sake of an example):
1) create a big list of strings for playing around purpose
from random import choice
from string import ascii_uppercase
import time
oldlist = ([''.join(choice(ascii_uppercase)
for i in range(10)) for x in range(1000000)])
2) process it using loop, list comprehension, and maps loop variant 1:
start_time = time.time()
newlist = []
for word in oldlist:
newlist.append(word.lower())
print(time.time()-start_time) # 0.1368732452392578
loop variant 2:
start_time = time.time()
newlist = []
append = newlist.append
for word in oldlist:
append(word.lower())
print(time.time()-start_time)# 0.1112520694732666
list comp:
start_time = time.time()
newlist = [word.lower() for word in oldlist]
print(time.time()-start_time) # 0.07511067390441895
map:
start_time = time.time()
newlist = map(str.lower, oldlist)
print(time.time()-start_time) # 3.0994415283203125e-06
Can I assume that in such situation map should always be used as its faster than the rest? List comprehension is considered more readable according to various articles but should readability be the first priority or a significant amount of speed?
Note: I just took an average of five iterations so these times values might change a bit. However, it gives us an indication. Python version: 3