If you want to run a function over every member of an iterable, like a list, you can do that in three ways: an explicit for
statement, a call to the map
function, or a comprehension.
A comprehension looks like this:
my_new_strings = [re.sub(r'\W+', '', my_string) for my_string in my_strings]
But, even if you read the tutorial sections above, this may not make sense unless you first think about how to write it with an explicit loop:
my_new_strings = []
for my_string in my_strings:
my_new_string.append(re.sub(r'\W', '', my_string))
A comprehension is basically this pattern condensed. They're nice because they eliminate some boilerplate (which gets in the way of reading code, and provides more places to make mistakes while writing code), can be used in the middle of an expression, and are a little faster. But ultimately, they do the same thing.