Friday, January 10, 2025
HomeComputer SciencePython - How to Create List of Lists

Python – How to Create List of Lists

In Python, a list of lists is essentially a two-dimensional list where each element of the main list is itself a list. Here’s how to create and work with a list of lists:

1. Using Nested Square Brackets

You can manually create a list of lists by nesting square brackets.

Example:

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

print(list_of_lists)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

2. Using a Loop

A loop can be used to create a list of lists dynamically.

Example:

python
# Creating a 3x3 list of lists
rows, cols = 3, 3
list_of_lists = [[0 for _ in range(cols)] for _ in range(rows)]

print(list_of_lists)
# Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

3. Using List Comprehension

List comprehension is a concise way to create a list of lists.

Example:

python
# Creating a list of lists with incrementing values
list_of_lists = [[j for j in range(1, 4)] for i in range(3)]

print(list_of_lists)
# Output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

4. Appending Lists to a Main List

You can append individual lists to create a list of lists.

Example:

python
list_of_lists = []
for i in range(3):
sub_list = [i * j for j in range(1, 4)]
list_of_lists.append(sub_list)

print(list_of_lists)
# Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

5. Creating an Empty List of Lists

To initialize an empty list of lists:

Example:

python
list_of_lists = [[] for _ in range(3)]

print(list_of_lists)
# Output: [[], [], []]

Accessing Elements in a List of Lists

You can access elements using double indexing.

Example:

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

# Accessing the second element of the first list
print(list_of_lists[0][1]) # Output: 2

# Accessing the third element of the second list
print(list_of_lists[1][2]) # Output: 6

Summary

  • Manual Creation: Use nested square brackets.
  • Dynamic Creation: Use loops or list comprehensions.
  • Modification: Append or update individual sublists as needed.

A list of lists is a powerful structure for handling grid-like data or nested information efficiently in Python.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x