Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Making a 2D List in Python

Learn how to create and manipulate 2D lists in Python, a fundamental concept for any aspiring Python programmer. …


Updated May 13, 2023

Learn how to create and manipulate 2D lists in Python, a fundamental concept for any aspiring Python programmer.

What is a 2D List?

In the context of programming, a 2D list (also known as a matrix or two-dimensional array) is a data structure that consists of rows and columns. Each element in the list is identified by its row index and column index. Think of it like a spreadsheet where each cell contains a value.

How Does a 2D List Relate to Lists in Python?

In Python, a list is an ordered collection of values. A 2D list can be thought of as a nested list, where each inner list represents a row in the matrix. This means that creating a 2D list in Python involves nesting one or more lists within another list.

Step-by-Step Guide to Creating a 2D List

Method 1: Using Nested Lists

# Create a 2D list with 3 rows and 4 columns
my_2d_list = [[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12]]

In this example, my_2d_list is a list containing three inner lists. Each inner list represents a row in the matrix.

Method 2: Using a List Comprehension

# Create a 2D list with 3 rows and 4 columns using list comprehension
my_2d_list = [[i * j for j in range(1, 5)] for i in range(1, 4)]

This method uses a nested list comprehension to create the 2D list. The outer loop generates the row indices (1-3), and the inner loop generates the column values (1-4).

Method 3: Using the numpy Library

import numpy as np

# Create a 2D list with 3 rows and 4 columns using numpy
my_2d_list = np.array([[1, 2, 3, 4],
                       [5, 6, 7, 8],
                       [9, 10, 11, 12]])

This method uses the numpy library to create a 2D array (also known as a matrix).

Accessing and Manipulating 2D Lists

Once you have created a 2D list, you can access and manipulate its elements using standard Python indexing and slicing syntax. For example:

# Access the first row in my_2d_list
print(my_2d_list[0])

# Access the second column in each row
for row in my_2d_list:
    print(row[1])

Conclusion

In this article, we have explored how to create a 2D list in Python using nested lists, list comprehensions, and the numpy library. We have also discussed how to access and manipulate the elements of a 2D list using standard Python indexing and slicing syntax. With practice and experience, you will become proficient in working with 2D lists and take your Python programming skills to the next level!

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp