Chris
Chris

Reputation: 5834

How do you turn a list of strings into a list of sublists with each string in each sublist?

How do you turn a list of strings into a list of sublist of strings?

For example:

List_of_Strings = ['abc','def','ghi']

Desired Output:

[['abc'],['def'],['ghi']]

My hack to get it is:

List_of_Sublist_of_Strings = [(str(x)+",").split(",") for x in List_of_Strings]

Produces:

[['abc', ''], ['def', ''], ['ghi', '']]

This produces an unwanted empty item in the sublists, but perhaps it's not possible to create a list of sublists in which the sublists only have one item.

Upvotes: 0

Views: 948

Answers (2)

user2555451
user2555451

Reputation:

Use a list comprehension like so:

>>> lst = ['abc','def','ghi']
>>> [[x] for x in lst]
[['abc'], ['def'], ['ghi']]
>>>

Putting x in [] places it in a list of its own.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

You need to put those strings in [] there, and it's done.

>>> lis =  ['abc','def','ghi']
>>> [[x] for x in lis]
[['abc'], ['def'], ['ghi']]

Upvotes: 3

Related Questions