3

With list of strings x:

x = ['foo', 'bar']

How can I do the following in one line?

y = []
for word in x:
    y.append([n for n in word])
print y

Resulting in:

[['f', 'o', 'o'], ['b', 'a', 'r']]

3 Answers 3

5

With list and simple list comprehension:

>>> x = ['foo', 'bar']
>>> y = [list(word) for word in x]
>>> y
[['f', 'o', 'o'], ['b', 'a', 'r']]

or by using map with list:

>>> y = map(list, x)
>>> y
[['f', 'o', 'o'], ['b', 'a', 'r']]
Sign up to request clarification or add additional context in comments.

Comments

3

You can create a list from each string within a list comprehension.

>>> x = ['foo', 'bar']
>>> [list(i) for i in x]
[['f', 'o', 'o'], ['b', 'a', 'r']]

Comments

3
>>> map(list, ['foo', 'bar'])
[['f', 'o', 'o'], ['b', 'a', 'r']]

Comments

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.