How to go from list comprehension to loop in this case?

Viewed 41

I have to perform the following action without using list comprehensions. I have a list that looks like the following one:

["Mi Fa Sol", 'Mi', "Mi Fa Sol La Si", "Do Si", " Mi Si Fa", "Fa"]

What I want to obtain is a list like the following one:

["Mi", "Fa", "Sol", "Mi", "Mi", "Fa", "Sol", "La", "Si", "Do", "Si", "Mi", "Si", "Fa", "Fa"]

I can do that in the following way, I think:

    lst = [elem.strip().split() for elem in lst]
    lst = [elem for sub_lst in lst for elem in sub_lst]

But I have no idea how to accomplish the same result without list comprehensions.

2 Answers

Your current version using two separate list comprehensions can be simplified to use a single list comprehension instead:

lst = [e for elem in lst for e in elem.split()]

But, if you want to use a traditional for loop instead, then you can loop through each elem of lst as you currently do, and use list.extend() to add the splitted elements to a result list res:

lst = ["Mi Fa Sol", 'Mi', "Mi Fa Sol La Si", "Do Si", " Mi Si Fa", "Fa"]
res = []
for elem in lst:
    res.extend(elem.split())
print(res)

Output:

['Mi', 'Fa', 'Sol', 'Mi', 'Mi', 'Fa', 'Sol', 'La', 'Si', 'Do', 'Si', 'Mi', 'Si', 'Fa', 'Fa']

You can assign res back to lst if needed afterwards.

Side note: since you use the default delimiter for split(), you can also omit the redundant strip() in this case.

Here's a functional approach:

>>> music = ["Mi Fa Sol", 'Mi', "Mi Fa Sol La Si", "Do Si", " Mi Si Fa", "Fa"]
>>> reduce(lambda x, y: x + y, map(str.split, music))
['Mi', 'Fa', 'Sol', 'Mi', 'Mi', 'Fa', 'Sol', 'La', 'Si', 'Do', 'Si', 'Mi', 'Si', 'Fa', 'Fa']

The lambda expression could be replaced by operator.add:

>>> import operator
>>> reduce(operator.add, map(str.split, music))
['Mi', 'Fa', 'Sol', 'Mi', 'Mi', 'Fa', 'Sol', 'La', 'Si', 'Do', 'Si', 'Mi', 'Si', 'Fa', 'Fa']

For the snippets above to work in work in Python 3 you have to include this sentence:

from functools import reduce
Related