Search code examples
pythonlistchars

Get the characters from a list of lists


I have this example :

example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]

So , I want to get the following array:

chars2=[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f','h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's'],['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]

I tried this:

chars2=[]
for list in example:
    for string in list:
        chars2.extend(string)

but i get the following:

['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']

Solution

  • For each list in example you need to add another list inside chars2 , currently you are just extending chars2 directly with each character.

    Example -

    chars2=[]
    for list in example:
        a = []
        chars2.append(a)
        for string in list:
            a.extend(string)
    

    Example/Demo -

    >>> example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]
    >>> chars2=[]
    >>> for list in example:
    ...     a = []
    ...     chars2.append(a)
    ...     for string in list:
    ...         a.extend(string)
    ...
    >>> chars2
    [['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' '], ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]