Home > Software design >  how to convert a list of strings into a list of letters in python?
how to convert a list of strings into a list of letters in python?

Time:09-16

How do I turn this:

list = ['hi', 'my', 'name', 'is']

into this:

list = ['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']

CodePudding user response:

Try:

l = ['hi', 'my', 'name', 'is']
output = list(''.join(l))
print(output)

Output:

['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']

CodePudding user response:

You can leverage the fact that you can iterate over a string just like a list:

words = ['hi', 'my', 'name', 'is']
letters = [letter for word in words for letter in word]
print(letters)

Output:

['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']

CodePudding user response:

Edited, tip from @juanpa.arrivillaga

list = ['hi', 'my', 'name', 'is']

newList = []
for x in list: 
    for y in x: 
        newList.append(y)

print(newList)

Output:

['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']
  • Related