-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
  • 112,593
  • 23
  • 157
  • 280
  • 1
    I didn't [downvote your question because no attempt was made](http://idownvotedbecau.se/noattempt) since you're a new contributor, but normally we expect you to at least make an [honest attempt at the solution](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), and _then_ ask specific question(s) about your implementation. – martineau Oct 29 '21 at 18:25
  • https://stackoverflow.com/a/69781225/4650634 – PersianMan Oct 30 '21 at 20:29

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
  • 81,317
  • 8
  • 19
  • 49
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,296
  • 1
  • 17
  • 25
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
  • 140
  • 8