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 into 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 as 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 item within 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 matrix you can use nested for loop like 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 new list into 2D list by using 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

Leave a Reply

Your email address will not be published. Required fields are marked *