Lina
Lina

Reputation: 11

A list of string into a nested list of string

so I need to turn a list of str into a list of list of str.

EX:

thing = [' a b c', 'e f g']

into:

[['a', 'b', 'c'], ['e', 'f', 'g']]

My code keeps returning a mistake:

coolthing = []   
abc = []
for line in thing:
    abc = coolthing.append(line.split())
return abc

Upvotes: 0

Views: 1600

Answers (1)

user2555451
user2555451

Reputation:

list.append operates in-place and always returns None. So, abc will be None when you return it.

To do what you want, you can use a list comprehension:

return [x.split() for x in thing]

Demo:

>>> thing = [' a b c', 'e f g']
>>> [x.split() for x in thing]
[['a', 'b', 'c'], ['e', 'f', 'g']]

Upvotes: 3

Related Questions