-2

Suppose I have a function that cleans a string (ex. make the string all uppercase letters and etc).

def clean_string(s)

How do I apply this function to strings in a list and return a cleaned list? I think this uses for loops but I just can't get around it.

allmine
  • 375
  • 1
  • 3
  • 9

2 Answers2

2

List comprehensions are the modern way to do this:

new_string = [clean_string(s) for s in your_list]
hd1
  • 33,938
  • 5
  • 80
  • 91
1

That's exactly what map() function is for:

map(clean_string, your_list)

Note:In python 3.X map returns an iterator which is more optimized in terms of memory use, but if you want to get a list you can use list() function to convert the result to list, or better you can use a list comprehension

[clean_string(item) for item in your_list]

But if you are dealing with large data and you just want to loop over the result you better to use map() in in python 3.X or a generator expression in python 2.X.

Mazdak
  • 105,000
  • 18
  • 159
  • 188