Home > Software engineering >  Splitting a list of n words into n lists of single words
Splitting a list of n words into n lists of single words

Time:09-30

I have got a list of sublists with potentially multiple words:

l = [['word1'], ['word2'], ['word1'], ['word1', 'word3'], ['word4']]

I want to get a list of sublists where each sublist is constituted of only one word such that:

l = [['word1'], ['word2'], ['word1'], ['word1'], ['word3'], ['word4']]

I wrote:

for i in l:
    if len(i) > 1 : 
        [l.append([j]) for j in i]
        l.remove(i)

print(l)

It appears to work (even if the words of the splitted sublist go at the end of the list), but the list comprehension prints:

[None, None]

What is the reason for this? Is there a better way of doing?

CodePudding user response:

A nested list comprehension will do that in one line:

[ [word] for wlist in l for word in wlist ]

[['word1'], ['word2'], ['word1'], ['word1'], ['word3'], ['word4']]

CodePudding user response:

I think this will work

for i in l:
    if len(i) > 1 :
        for j in i:
            l.append([j]) 
        l.remove(i)

print(l)
  • Related