Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a list of strings into a list of sublists of the individual characters in the strings?

So I am starting with:

['BLUE', 'ORANGE', 'YELLOW', 'GREEN', 'BLACK', 'PURPLE', 'BROWN']

and I want:

[['B', 'L', 'U', 'E'], ['O', 'R', 'A', 'N', 'G', 'E'], ['Y', 'E', 'L', 'L', 'O', 'W'], ['G', 'R', 'E', 'E', 'N'], ['B','L', 'A', 'C', 'K'], ['P', 'U', 'R', 'P', 'L', 'E'], ['B', 'R', 'O', 'W','N']]

I tried this because it looked like it would produce what I wanted but it keeps telling me I have an error. AttributeError: 'NoneType' object has no attribute 'append':

first_list = ['BLUE', 'ORANGE', 'YELLOW', 'GREEN', 'BLACK', 'PURPLE', 'BROWN']
list_1 = []

for i in range (len(first_list)):
    list_1 = list_1.append(list(first_list[i]))

return list_1

I keep having trouble using the ".append" and keep using "+" in other iterations but that just gives me a long list of all the characters instead of a list of sublists of characters. Thank you for any help or advice.

like image 377
Israel CA Avatar asked Jan 30 '26 16:01

Israel CA


1 Answers

The built-in list() function creates a list from an iterable object. Since a string is an iterable object, we can pass it to list() to create a list of the individual characters. To do this for each of the words, we can use a list comprehension:

>>> words = ['BLUE', 'ORANGE', 'YELLOW', 'GREEN', 'BLACK', 'PURPLE', 'BROWN']
>>> [list(word) for word in words]
[['B', 'L', 'U', 'E'], ['O', 'R', 'A', 'N', 'G', 'E'], ['Y', 'E', 'L', 'L', 'O', 'W'], ['G', 'R', 'E', 'E', 'N'], ['B', 'L', 'A', 'C', 'K'], ['P', 'U', 'R', 'P', 'L', 'E'], ['B', 'R', 'O', 'W', 'N']]

Edit: the attribute error you were getting is because the append() method of a list returns None. Since you assign the output of the method to the list1 variable, you overwrite the list with None on the first time around the loop. Since None does not have a append method, on the next time around the loop you get the error. Removing this assignment makes your code work:

>>> first_list = ['BLUE', 'ORANGE', 'YELLOW', 'GREEN', 'BLACK', 'PURPLE', 'BROWN']
>>> list_1 = []
>>> for i in range (len(first_list)):
...     list_1.append(list(first_list[i]))
... 
>>> list_1
[['B', 'L', 'U', 'E'], ['O', 'R', 'A', 'N', 'G', 'E'], ['Y', 'E', 'L', 'L', 'O', 'W'], ['G', 'R', 'E', 'E', 'N'], ['B', 'L', 'A', 'C', 'K'], ['P', 'U', 'R', 'P', 'L', 'E'], ['B', 'R', 'O', 'W', 'N']]
like image 136
Blair Avatar answered Feb 02 '26 08:02

Blair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!