Importance of list comprehensions in Python

A beginner to python programming is usually taught to use for loops to do a lot things. The temptation  is to bust out a for loop whenever you need to modify a list or string object, but this quickly leads to complex “loops within loops” code architectures that are hard to read (by humans), even though they may work OK.

A simple example:

>>>test_list = [2,4,6,8]

>>>for x in test_list:

…     new_list.append(x  + 1)



A better approach is to take advantage of Python’s built-in list comprehension expressions, with the form ‘x for x in y’.


>>>new_list = [x+2 for x in test_list]



This can be expanded to include conditionals, for example:

>>>stripped_list = [line.strip() for line in line_list if line !=””]

You can also loop over multiple elements like this:



>>>[(x,y) for x in seq1 for y in seq2]


Leave a Reply

Your email address will not be published.