Convert List of Strings to List of Lists using List Comprehension

Viewed 180

I tried this:

l = ['cat', 'dog', 'fish']
ll = [list(x) for x in l]
print(ll)

and I got this

[['c', 'a', 't'], ['d', 'o', 'g'], ['f', 'i', 's', 'h']]

what I need is

[['cat'], ['dog'], ['fish']]
4 Answers

Instead of calling the list constructor (which breaks the string down to its characters) simply:

ll = [[x] for x in l]

For each iteration over the elements of l, this creates a nested list with the single item x in it.

You can try this:

l = ['cat', 'dog', 'fish']
ll = [[x] for x in l]
print(ll)

This converts every element to an array. What you are doing with the list() function is converting a word to an array of characters.

just return a list instead of spliting the strings:

l = ['cat', 'dog', 'fish']
ll = [[x] for x in l]
print(ll)

If the output you are looking for is actually

[['cat'], ['dog'], ['fish']]

Then the solution, as provided above, is the list comprehension with the square brackets wrapper:

l = ['cat', 'dog', 'fish']
ll = [[x] for x in l]
print(ll)

Output:

[[cat], [dog], [fish]]

However, if the output you're looking for the exactly the one you displayed in your post, then you'll need to use a formatted string:

l = ['cat', 'dog', 'fish']
ll = f"[[{'] ['.join(l)}]]"
print(ll)

Output:

[[cat], [dog], [fish]]
Related