Python: Simple for loops

For example you have a piece of code that runs through and performs an operation on each item in a list.

items = [ 'hello', 'there', 'blah' ]

for i in range(len(items)):
items[i] = items[i].replace('e', 'i')

You can turn it into a 1 line wonder by changing it to:

items = map(lambda x: x.replace('e', 'i'), items)

Or you could just use what triclops mentioned which is MUCH simpler...
items = [word.replace('e', 'i') for word in items]
 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog