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)
>>>new_list
[3,5,7,9]
A better approach is to take advantage of Python’s built-in list comprehension expressions, with the form ‘x for x in y’.
Example:
>>>new_list = [x+2 for x in test_list]
>>>new_list
[4,6,8,10]
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:
>>>seq1=’abc’
>>>seq2=(1,2,3)
>>>[(x,y) for x in seq1 for y in seq2]
[(‘a’,1),(‘a’,2),(‘a’,3),(‘b’,1),(‘b’,2)….(‘c’,3)]