2

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']]
3
  • 1
    Is your expected output supposed to be the expected printed output? This is not a valid Python object unless you have defined variables cat and so on... Commented Mar 14, 2021 at 14:19
  • @ThierryLathuille Great catch. I went back and added the quotes in my desired output. Thank you, Commented Mar 14, 2021 at 14:55
  • 1
    Does this answer your question? How to wrap each item of a list into its proper list Commented Mar 17, 2021 at 9:23

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

4

just return a list instead of spliting the strings:

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

Comments

0

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]]

1 Comment

Yes, I did want the quoted strings in the output. Thank you for catching that.

Your Answer

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.