Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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']]
With list and simple list comprehension:
list
>>> x = ['foo', 'bar'] >>> y = [list(word) for word in x] >>> y [['f', 'o', 'o'], ['b', 'a', 'r']]
or by using map with list:
map
>>> y = map(list, x) >>> y [['f', 'o', 'o'], ['b', 'a', 'r']]
Add a comment
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']]
>>> map(list, ['foo', 'bar']) [['f', 'o', 'o'], ['b', 'a', 'r']]
Required, but never shown
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.
Explore related questions
See similar questions with these tags.