-1

Having a Python list like the following one:

list1 = [ "abc", "def", "ghi" ]

How can I obtain sub-lists for each character of the strings ?

list3 = [ ["a"], ["b"], ["c"] ]

list4 = [ ["d"], ["e"], ["f"] ]

list5 = [ ["g"], ["h"], ["i"] ]
martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

2

Do not generate variables programmatically, this leads to unclear code and is often a source of bugs, use a container instead (dictionaries are ideal).

Using a dictionary comprehension:

list1 = [ "abc", "def", "ghi" ]

lists = {'list%s' % (i+3): [[e] for e in s]] 
         for i,s in enumerate(list1)}

output:

>>> lists
{'list3': [['a'], ['b'], ['c']],
 'list4': [['d'], ['e'], ['f']],
 'list5': [['g'], ['h'], ['i']]}

>>> lists['list3']
[['a'], ['b'], ['c']]

NB. you could also simply use the number as key (3/4/5)

mozway
  • 194,879
  • 13
  • 39
  • 75
2

To get a list from a string use list(string)

list('hello') # -> ['h', 'e', 'l', 'l', 'o']

And if you want to wrap the individual characters in a list do it like this:

[list(c) for c in 'hello'] # --> [['h'], ['e'], ['l'], ['l'], ['o']]

But that is useful only if you want to change the list afterward.

Note that you can index a string like so

'hello'[2] # --> 'l'
nadapez
  • 2,603
  • 2
  • 20
  • 26
0

This is how to break a list then break it into character list.

list1 = ["abc", "def", "ghi"]
list3 = list(list1[0])
list4 = list(list1[1])
list5 = list(list1[2])
Harry Lee
  • 150
  • 9