Reputation: 35
list1=[1, 2, 3, 4, 5]
I want to create a list [[1, 2, 3, 4, 5]]
from list1
.
I tried list(list1)
but it's showing only [1, 2, 3, 4, 5]
instead of [[1, 2, 3, 4, 5]]
.
Upvotes: 3
Views: 892
Reputation: 12669
One line solution :
list1=[1, 2, 3, 4, 5]
print([[nested_list for nested_list in list1]])
or just use:
list1=[1, 2, 3, 4, 5]
nested_list=[list1]
Upvotes: 0
Reputation: 20414
Just initialise a new list
which has a sub-list
that is list1
.
This is done with:
[list1]
which will give:
[[1, 2, 3, 4, 5]]
Or alternatively, when you are defining list1
, you can define it already nested
inside another list
:
list1 = [[1, 2, 3, 4, 5]]
Note that when you were trying to nest
the original list
inside another list
, using list()
will not work.
If you read the documentation:
The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].
The key thing mentioned here is that list
creates a list
from an iterable
. As list1
is a list
already, it is an iterable
. This means that the list()
constructor will treat as an iterable
and create a new list
from the elements
inside list1
- creating a copy of it. So that is why it wasn't working as you expected it to.
Upvotes: 1
Reputation: 7399
You'll have to put it in another list using. When you declare a list, you put them in two square brackets. If you want to make a list of lists, you'll have to use them twice.
lis = [your_list]
Upvotes: 0