How to Create a 2D List in Python
A step-by-step guide to creating and working with 2D lists in Python, covering the essentials of multidimensional data storage.| …
Updated July 5, 2023
|A step-by-step guide to creating and working with 2D lists in Python, covering the essentials of multidimensional data storage.|
Definition of the Concept
In Python, a 2D list, also known as a list of lists or multidimensional array, is a data structure that stores multiple values in a rectangular format. Each element within the 2D list can itself be another list containing one or more values.
Think of it like an Excel spreadsheet where each row and column are separate lists, but together they form a larger multidimensional dataset.
Step-by-Step Explanation
Creating a 2D list in Python involves several steps:
Step 1: Define the Outer List (Rows)
First, you need to define the outer list, which represents each row of your data. This can be done using square brackets []
and placing lists inside them.
# Example 1: Defining a single row
row = [10, 20, 30]
print(row) # Output: [10, 20, 30]
# Example 2: Multiple rows in the same list (but not a 2D list yet)
rows = [[10, 20], [30, 40]]
print(rows) # Output: [[10, 20], [30, 40]]
As you see from the second example, we’ve defined multiple lists inside another list, but this is still not a true 2D list.
Step 2: Convert to a True 2D List
To actually create a 2D list where each element can be another list or even just one value, you need to nest your lists correctly. The correct way to define a 2D list in Python involves using nested square brackets []
.
# Correctly defining a true 2D list (matrix)
two_d_list = [[1, 2], [3, 4]]
print(two_d_list) # Output: [[1, 2], [3, 4]]
# Accessing individual elements in the 2D list
print(two_d_list[0][0]) # Output: 1 (Accesses first element)
Note how we access elements within a 2D list. You need to specify both the row and column index within the square brackets.
Conclusion
Creating a 2D list in Python is straightforward once you understand the concept. It involves defining nested lists where each inner list can represent rows or even single values, depending on your use case. Understanding how to correctly nest your lists ensures that you’re working with true multidimensional data structures.