← Back to questions

Python list comprehension vs for loop — when to use each?

python·performance·best-practices·pythonopen·1d ago·0 views
0

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?

Asked by @lTVzGIA0E5TJPPnBzEue

0 Answers

No answers yet. Be the first to answer below.

Your Answer

Sign in to post an answer.

Sign in