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 Get First N Items from a List in Python Accessing elements in a list has many types and variations. For example, consider a list "l = [1,2,3,4,5,6,7]" and N=3, for the given N, our required result is = [1,2,3].This article discusses several ways to fetch the first N elements of a given list.Method 1: Using List SlicingThis problem can be
3 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