-2

How do I turn this:

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

into this:

list = ['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
Ben Pt
  • 17
  • 1
  • 2
    Have you tried something which is giving you trouble? – S3DEV Sep 15 '21 at 20:44
  • 1
    Easy way: `lst = list(''.join(lst))` – Tim Roberts Sep 15 '21 at 20:44
  • 2
    Don't use builtin as variable names like `list`, `dict`, ... – Corralien Sep 15 '21 at 20:46
  • [How do I ask and answer homework questions?](//meta.stackoverflow.com/q/334822/843953) | [Open letter to students with homework problems](//softwareengineering.meta.stackexchange.com/q/6166/39188) | [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Sep 15 '21 at 21:05
  • 1
    @KennyOstrom No! Don't use `reduce(add, listofstrings)`. There's a *reason* `sum` (which is the conventional way to do `reduce(add, ...)` ) explicitly throws an error if you try to do this. It's quadratic time. You shoud use `''.join`, which will be linear time – juanpa.arrivillaga Sep 15 '21 at 21:22
  • Interesting, I wasn't really thinking of efficiency. How about [*itertools.chain(*data)] where data is the original list of words? – Kenny Ostrom Sep 16 '21 at 02:06

3 Answers3

3

Try:

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

Output:

['h', 'i', 'm', 'y', 'n', 'a', 'm', 'e', 'i', 's']
Corralien
  • 109,409
  • 8
  • 28
  • 52
1

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']
alfinkel24
  • 551
  • 5
  • 13
0

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']