Python: Simple for loops

2 Comments

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

1.items = [ 'hello', 'there', 'blah' ]
2. 
3.for i in range(len(items)):
4.items[i] = items[i].replace('e', 'i')

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

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


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