How to Create a List of Lists in Python Using a Single List?

Estimated read time 1 min read

In Python, you can create a list of lists using a single list and some slicing operations. Here’s an example:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
size = 3
my_new_list = [my_list[i:i+size] for i in range(0, len(my_list), size)]

In this example, we first define a list my_list containing nine integers. We then define a variable size that specifies the length of each sublist we want to create. We then create a new list my_new_list using a list comprehension that iterates over the indices of my_list using the range() function. For each index i, we slice my_list from i to i+size, creating a sublist of length size. Finally, we append each sublist to my_new_list.

The result is a list of three sublists, each containing three integers:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

You can modify the value of size to create sublists of different lengths or modify the contents of my_list to create different sublists.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply