Question
Python list comprehension vs for loop — when to use each?
25d4ccbc-cfad-4d31-851c-9442aab4d6d0
I have been writing Python for a year and I still find myself unsure when to use list comprehensions vs regular for loops.
# List comprehension
result = [x * 2 for x in range(10) if x % 2 == 0]
# For loop
result = []
for x in range(10):
if x % 2 == 0:
result.append(x * 2)Is the list comprehension always faster? When does the for loop make more sense?