3

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

4
  • 1
    If you ask a question about lists, it's usually implied that numpy isn't a necessity to solve the problem... just a heads up. Also please don't use the tag arrays if you're talking about lists. Commented Oct 28, 2017 at 13:29
  • list([list1]) does it for me. Commented Oct 28, 2017 at 13:30
  • 1
    what about [list1] ? Commented Oct 28, 2017 at 13:33
  • Think carefully about the logic. How many elements should the new list contain? (Hint: One.) What should the first element be? (Hint: list1.) How do you write code that means "a list with one element, where that element is list1"? Commented Aug 26, 2023 at 14:15

5 Answers 5

1

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.

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

Comments

0

Have you tried?

list2 = [list1]

Comments

0

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]

1 Comment

list() is redundant
0

This works for me

list1=list([list1])

Comments

0

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]

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.