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!

Creating a 2D List in Python

Learn how to create and manipulate 2D lists in Python, perfect for storing and working with data.| …


Updated July 22, 2023

|Learn how to create and manipulate 2D lists in Python, perfect for storing and working with data.|

Definition of a 2D List

A 2D list, also known as a matrix or nested list, is a list that contains other lists as its elements. It’s an array of arrays in Python, allowing you to store multiple values in a structured format.

Why Use 2D Lists?

2D lists are useful for storing and manipulating data in a tabular format, making it ideal for tasks like:

  • Creating matrices for linear algebra calculations
  • Representing game boards or maps
  • Storing and analyzing data from sensors or other sources

Step-by-Step Explanation: Creating a 2D List

Here’s how to create a simple 2D list in Python:

Method 1: Using Square Brackets []

# Create an empty 2x3 2D list
two_d_list = [[] for _ in range(2)]

# Fill the lists with values
for i in range(len(two_d_list)):
    two_d_list[i] = [i*10, i*20, i*30]

print(two_d_list)

Output:

[[0, 10, 20], [20, 40, 60]]

In this example:

  1. We create an empty list using the [] syntax.
  2. We use a for loop to populate each inner list with values.

Method 2: Using List Comprehensions

# Create a 3x4 2D list with values ranging from 0 to 15
two_d_list = [[i*5 + j for j in range(4)] for i in range(3)]

print(two_d_list)

Output:

[[0, 5, 10, 15], [10, 15, 20, 25], [20, 25, 30, 35]]

In this example:

  1. We use a nested list comprehension to create the 2D list.
  2. The outer loop iterates over i (the row), and the inner loop populates each column with values.

Accessing and Manipulating Elements in a 2D List

To access or modify elements in a 2D list, you can use standard indexing techniques:

# Create a sample 3x4 2D list
two_d_list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

# Accessing an element at position (1, 3)
print(two_d_list[1][3])  # Output: 8

# Modifying an element at position (2, 2)
two_d_list[2][2] = 99
print(two_d_list)  # Output: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 99, 12]]

Conclusion

Creating a 2D list in Python is a straightforward process that allows you to store and manipulate data in a structured format. By understanding how to create and work with 2D lists, you can efficiently perform various tasks, from linear algebra calculations to game development.

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

Intuit Mailchimp