How to Create a List of N-Lists in Python
Last Updated :
11 Sep, 2024
In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python.
The different approaches that we will cover in this article are:
Creating a list of N-lists in Python, each with a different memory location
To achieve distinct memory locations for each sublist, you should create each sublist independently. Here are a few methods to do this:
Example 1: Using List comprehension
In this example, we are using list comprehension for generating a list of lists.
Python
# Create a list of 6 independent sublists using list comprehension
d1 = [[] for x in range(6)]
print("Initial list:", d1)
# Print memory addresses of each sublist
for i in range(len(d1)):
print(f"Memory address of d1[{i}]:", id(d1[i]))
# Modify the first sublist by appending the value 2
d1[0].append(2)
print("Modified list:", d1)
# Print memory addresses again to confirm they haven't changed
for i in range(len(d1)):
print(f"Memory address of d1[{i}] after modification:", id(d1[i]))
Output[[], [], [], [], [], []]
[[2], [], [], [], [], []]
Example 2: Using a loop
In this example, we are creating a list using a loop with a range of 6 and appending lists into a list.
Python
N = 5
lists = []
# Create a list with N independent empty sublists
for _ in range(N):
lists.append([])
# Print initial state
print("Initial lists:", lists)
# Print memory addresses of each sublist
for i in range(len(lists)):
print(f"Memory address of lists[{i}]:", id(lists[i]))
# Modify the first sublist by appending the value 2
lists[0].append(2)
# Print modified state
print("Modified lists:", lists)
# Print memory addresses again to confirm they haven't changed
for i in range(len(lists)):
print(f"Memory address of lists[{i}] after modification:", id(lists[i]))
Output[[], [], [], [], []]
[[2], [], [], [], []]
Creating a list of N-lists in Python, each with a same memory location
Creating a list of N-lists in Python, each with a different memory location, involves ensuring that each sublist is a distinct object. This is important to avoid unintended side effects where modifying one sublist affects others.
Example 1: Using simple multiplication
In this example, we are multiplying the list by 4 to get a list of lists.
Python
# Create a list with 4 references to the same sublist
lis = [[]] * 4
print("Initial list:", lis)
# Print memory addresses of each sublist
for i in range(len(lis)):
print(f"Memory address of lis[{i}]:", id(lis[i]))
# Modify the first sublist
lis[0].append(2)
print("Modified list:", lis)
# Print memory addresses again to confirm they haven't changed
for i in range(len(lis)):
print(f"Memory address of lis[{i}] after modification:", id(lis[i]))
Output[[], [], [], []]
[[2], [2], [2], [2]]
Example 2: Using itertools
Using the built-in repeat function from the itertools module. This function allows you to repeat a given object a certain number of times, which can be useful for creating lists of lists.
Here is an example of how you can use repeat to create a list of lists in Python:
Python
from itertools import repeat
# Create a list of lists with 5 sub-lists using itertools.repeat
n_lists = list(repeat([], 5))
print("Initial list:", n_lists)
for i in range(len(n_lists)):
print(f"Memory address of n_lists[{i}]:", id(n_lists[i]))
# Modify the first sublist
n_lists[0].append(2)
print("Modified list:", n_lists)
# Print memory addresses again to confirm they haven't changed
for i in range(len(n_lists)):
print(f"Memory address of n_lists[{i}] after modification:", id(n_lists[i]))
Output[[], [], [], [], []]
[[2], [2], [2], [2], [2]]
Similar Reads
Create a List of Tuples in Python The task of creating a list of tuples in Python involves combining or transforming multiple data elements into a sequence of tuples within a list. Tuples are immutable, making them useful when storing fixed pairs or groups of values, while lists offer flexibility for dynamic collections. For example
3 min read
How to Find Length of a list in Python The length of a list means the number of elements it contains. In-Built len() function can be used to find the length of an object by passing the object within the parentheses. Here is the Python example to find the length of a list using len().Pythona1 = [10, 50, 30, 40] n = len(a1) print("Size of
2 min read
Break a List into Chunks of Size N in Python The goal here is to break a list into chunks of a specific size, such as splitting a list into sublists where each sublist contains n elements. For example, given a list [1, 2, 3, 4, 5, 6, 7, 8] and a chunk size of 3, we want to break it into the sublists [[1, 2, 3], [4, 5, 6], [7, 8]]. Letâs explor
3 min read
Ways to create a dictionary of Lists - Python A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
How to Initialize a List in Python Python List is an ordered collections on items, where we can insert, modify and delete the values. Let's first see how to initialize the list in Python with help of different examples. Initialize list using square brackets []Using [] we can initialize an empty list or list with some items. Python# I
2 min read
Python - Convert list of string to list of list In Python, we often encounter scenarios where we might have a list of strings where each string represents a series of comma-separated values, and we want to break these strings into smaller, more manageable lists. In this article, we will explore multiple methods to achieve this. Using List Compreh
3 min read
Ways to Iterate Tuple List of Lists - Python In this article we will explore different methods to iterate through a tuple list of lists in Python and flatten the list into a single list. Basically, a tuple list of lists refers to a list where each element is a tuple containing sublists and the goal is to access all elements in a way that combi
3 min read
Python List of Lists A list of lists in Python is a collection where each item is another list, allowing for multi-dimensional data storage. We access elements using two indices: one for the outer list and one for the inner list. In this article, we will explain the concept of Lists of Lists in Python, including various
3 min read
How to add Elements to a List in Python In Python, lists are dynamic which means that they allow further adding elements unlike many other languages. In this article, we are going to explore different methods to add elements in a list. For example, let's add an element in the list using append() method:Pythona = [1, 2, 3] a.append(4) prin
2 min read
Python | Ways to Convert a 3D list into a 2D list List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or w
3 min read