1

I am very new to python and i was stuck with this. I need to create a list of lists that is formed from this list c: ['asdf','bbnm','rtyu','qwer'].

I need to create something like this:

b: [['a','s','d','f'],['b','b','n','m'],['r','t','y','u'],['q','w','e','r']]

I tried using a for-loop, but it is not working out. I don't know what mistake I am making.

arshajii
130k26 gold badges246 silver badges293 bronze badges
asked Sep 29, 2013 at 16:57
3
  • Show us what you mean with "I tried", and what you mean "it is not working out". It's hard to tell what your mistake is otherwise. Commented Sep 29, 2013 at 17:00
  • That said, [list(s) for s in c] should work. list(x) converts any sequence into a list of its elements, and a str is a sequence of its characters. The surrounding stuff is a list comprehension. Commented Sep 29, 2013 at 17:00
  • Why do you need this? You can iterate over a string just as well as a list—what is it that strictly requires a list? Commented Sep 29, 2013 at 17:07

3 Answers 3

4

You can use a list comprehension with list():

>>> c = ['asdf','bbnm','rtyu','qwer']
>>> 
>>> b = [list(s) for s in c]
>>> b
[['a', 's', 'd', 'f'], ['b', 'b', 'n', 'm'], ['r', 't', 'y', 'u'], ['q', 'w', 'e', 'r']]

Notice that calling list() with a string argument returns a list containing the characters of that string:

>>> list('abc')
['a', 'b', 'c']

What we're doing above is applying this to every element of the list via the comprehension.

answered Sep 29, 2013 at 17:00

Comments

1

Use map function.

>>> a= ['asdf','bbnm','rtyu','qwer']
>>> map(list ,a )
[['a', 's', 'd', 'f'], ['b', 'b', 'n', 'm'], ['r', 't', 'y', 'u'], ['q', 'w', 'e', 'r']]
>>> 
answered Mar 5, 2014 at 12:38

Comments

-1

You could do something that's easier to understand:

b = []
for x in c:
 list(x).append(b)
answered Nov 9, 2016 at 0:06

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

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.

Ask question

Explore related questions

See similar questions with these tags.