Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I create a multidimensional list in Python?
Multidimensional lists are lists within lists that allow you to store data in a table-like structure. You access elements using two indices: the first for the row and the second for the column, like list[row][column].
Basic Structure
In a multidimensional list, each element can be accessed using bracket notation ?
list[r][c]
Where r is the row number and c is the column number. For example, a 2x3 multidimensional list would be accessed as list[2][3].
Creating a Multidimensional List
You can create a multidimensional list by nesting lists inside another list ?
# Create a Multi-Dimensional Python List
mylist = [[2, 5], [10, 24, 68], [80]]
print("Multidimensional List")
for row in mylist:
print(row)
Multidimensional List [2, 5] [10, 24, 68] [80]
Accessing Elements
Access specific elements using square brackets with two indices ?
# Create a Multi-Dimensional Python List
mylist = [[2, 5], [10, 24, 68], [80]]
print("Multidimensional List")
for row in mylist:
print(row)
# Accessing third element in the 2nd row (index 1, element 2)
print("\nThird element in the 2nd row =", mylist[1][2])
# Accessing first element in the 1st row
print("First element in the 1st row =", mylist[0][0])
Multidimensional List [2, 5] [10, 24, 68] [80] Third element in the 2nd row = 68 First element in the 1st row = 2
Adding Elements
Use the append() method to add new rows to a multidimensional list ?
# Create a Multi-Dimensional Python List
mylist = [[2, 5], [10, 24, 68], [80]]
print("Original Multidimensional List")
for row in mylist:
print(row)
# Append a new row
mylist.append([65, 24])
print("\nAfter appending [65, 24]:")
for row in mylist:
print(row)
# Append elements to an existing row
mylist[0].append(99)
print("\nAfter appending 99 to first row:")
for row in mylist:
print(row)
Original Multidimensional List [2, 5] [10, 24, 68] [80] After appending [65, 24]: [2, 5] [10, 24, 68] [80] [65, 24] After appending 99 to first row: [2, 5, 99] [10, 24, 68] [80] [65, 24]
Creating Regular Multidimensional Lists
For matrices with equal rows and columns, you can use list comprehension ?
# Create a 3x3 matrix filled with zeros
rows, cols = 3, 3
matrix = [[0 for j in range(cols)] for i in range(rows)]
print("3x3 Matrix:")
for row in matrix:
print(row)
# Fill with some values
matrix[0][0] = 1
matrix[1][1] = 5
matrix[2][2] = 9
print("\nAfter adding values:")
for row in matrix:
print(row)
3x3 Matrix: [0, 0, 0] [0, 0, 0] [0, 0, 0] After adding values: [1, 0, 0] [0, 5, 0] [0, 0, 9]
Conclusion
Multidimensional lists are created by nesting lists within lists. Use list[row][col] to access elements and append() to add new rows. For regular matrices, list comprehension provides an efficient creation method.
