0

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

1 Answer 1

3

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']]
Sign up to request clarification or add additional context in comments.

5 Comments

return map(str.split,thing) for a functional apporach
@PadraicCunningham - +1. I actually thought about doing that initially, but then you'd have to do return list(map(str.split,thing)) if the OP was using Python 3.x. Nice thing about the list comp. is it works the same in both versions.
Your way is probably better for the OP, just thought I would throw it in there.
Based on my rudimentary testing with timeit, the functional approach is nominally faster.
@pzp1997 - True. In Python 2.x, the map approach will be faster because most of the work (i.e. the looping) is being done in C and not Python. Note however that in Python 3.x, the list comp. outperforms list(map(str.split,thing)). Mainly though, I used the list comp. for portability. It also seems slightly more readable to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.