0

Here is an example of a list that I would like to convert into a list of lists in python:

p=[1,2,3,4]

I wrote the following code to address the problem:

u=[]
v=[x for x in p]
u.append(v)

my result: [[1,2,3,4]]

Result I would like to have: **[[1],[2],[3],[4]]**

Any suggestions? thanks.

3 Answers 3

6

Just make a small tweak to your list comprehension, and wrap the x in brackets to put each element in a list.

>>> p = [1, 2, 3, 4]
>>> v = [[x] for x in p]
>>> v
[[1], [2], [3], [4]]
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks Nitzle, I have solved similar problem in the past, but just couldn't think straight today.
2

You want something like this:

u = [[x] for x in p]

Comments

1

As other answer have depicted, List Comprehension is a straightforward way, but there are alternatives

>>> map(list,zip(p))
[[1], [2], [3], [4]]

or

>>> from itertools import izip
>>> map(list,izip(p))
[[1], [2], [3], [4]]

Comments

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.