How do I convert a Python list of integers into a list of lists?

I have a list of elements like this:

[1,2,3,4]

I need to convert them to a list of list since the output like this:

[[1],[2],[3],[4]]

I have searched for some answers using the map function or using the list keyword but it's throwing an error saying the integer is not iterable.

Any suggestions on how to do this?

Upvotes: 0

Views: 77

Answers (2)

Alex Riley
Alex Riley

Reputation: 176770

You can use list comprehension to build the list of lists:

>>> l = [1,2,3,4]
>>> [[x] for x in l]
[[1], [2], [3], [4]]

Or alternatively, map:

>>> list(map(lambda x: [x], l)) # list() not needed in Python 2
[[1], [2], [3], [4]]

Calling list() on a integer x won't work (as you state) because integers are not iterable (unlike, say, strings or tuples): you need to create a list containing x by writing [x].

Upvotes: 2

F.X.
F.X.

Reputation: 7317

The NumPy function atleast_2d can also be used, e.g:

>>> from numpy import atleast_2d
>>> a = [1, 2, 3, 4]
>>> atleast_2d(a).T
array([[1],[2],[3],[4]])

Upvotes: 0

Related Questions