2D Lists in Python

In this article, you will learn what are 2D lists in python and how to create, access, and add the new list to them. If you don’t know what are lists in python, then you should read the following recommended article:
Lists in python

What are 2D lists in python?

2D lists are very powerful and used in data science and machine learning. 2D lists in python can also be called multidimensional lists. The 2D list is a list in which each item is also a list. You can create a 2D list by creating a list like the following which is similar to a matrix.

Example:

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

Accessing the 2D list:

You can access items within the matrix by passing indexes between [][].

Example:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[0][0])

Output:

1

Looping through 2D lists:

To print all items in the matrix you can use nested for loop like the following:

Example:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
for row in matrix:
    for item in row:
        print(item)

Output:

1
2
3
4
5
6
7
8
9

Adding a new list in 2D list:

You can add a new list into the 2D list by using the built-in method appened().

Example:

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

matrix.append([10, 11, 12])
print(matrix)

Ouput:

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

Check out the Recommended Posts:

Tuples in python

Dictionary in python

Lists in python

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments