How to make a two -dimensional list in Python
Create a 2D list in Python with an example: learn how to use nested lists & multiple for loops to create a two-dimensional array.
Creating a 2D List in Python
A two-dimensional list, also known as a 2D list or a multi-dimensional list, is a list that contains other lists as its elements. This type of list is useful for representing a table of data or a matrix. Creating a two-dimensional list in Python is easy and straightforward.
To start, let’s say we want to create a two-dimensional list with three rows and four columns. We can do this by creating a list with three elements and each element is a list with four elements. We can do this using the following code:
twoD_list = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
This creates a 2D list with three rows and four columns. Each row is represented by its own list and each column is represented by its own element within each list. We can access a particular element of the list using two indices. The first index is the row number and the second index is the column number. For example, if we wanted to access the element in the first row and second column, we would use the following code:
element = twoD_list[0][1]
This would set the variable element
to the value 2. We can also use nested loops to iterate through the elements of the two-dimensional list. For example, the following code will print out all of the elements in the two-dimensional list:
for row in twoD_list:
for element in row:
print(element)
This code will print out the following output:
1
2
3
4
5
6
7
8
9
10
11
12
As you can see, creating a two-dimensional list in Python is quite straightforward and can be used to represent tables of data or matrices. It can also be used to iterate through the elements of the list using nested loops.