How to make a list of a list in Python

"Learn how to slice a list in Python with a simple example. Quickly master this essential programming skill for data manipulation!"

Making a List of a List in Python

Making a list of a list in Python is a relatively simple task. To begin with, you will need to define the list that you want to create a list of. For example, let's create a list of numbers.

list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8]

Now, let's create the list of the list. To do this, we can use a list comprehension. This is a way of creating a new list from an existing list. Let's use our list_of_numbers list to create a list of lists.

list_of_lists = [[num, num * 2] for num in list_of_numbers]

The above code will create a list of lists, where each list contains two elements, the number itself and its double. Let's see what we get when we print our list_of_lists.

print(list_of_lists) 

[[1, 2], [2, 4], [3, 6], [4, 8], [5, 10], [6, 12], [7, 14], [8, 16]]

As you can see, the list of lists contains all of the numbers from our original list, as well as the doubled value of each of those numbers. This is a simple example of how to create a list of a list in Python.

Answers (0)