The **list** is one of the most useful data-type in **python**. We can add values of all types like integers, string, float in a single list. List initialization can be done using square brackets []. Below is an example of a 1d list and 2d list. As we cannot use 1d list in every use case so **python 2d list** is used. Also, known as lists inside a list or a nested list. The number of elements in a 2d list will be equal to the no. of row * no. of columns. **A 2d list looks something like this. **

```
list1_d=[’sonu', 'ashu’, 50, 10.1]
list_2d=[ [5,6,7,7] , [5,4,6,7] , [9,8,9,10] ]
```

Contents

## Graphical Representation

Graphically a 2d list can be represented in the form of a grid.

## How to declare/initialize a 2d python list

There are multiple ways to initialize a 2d list in python.

- This is the basic approach for creating a 2d list in python.

```
rows=[]
columns=[]
for i in range(3):
for j in range(3):
columns.append(1)
rows.append(columns)
```

OUTPUT-

[[1, 1, 1], [1, 1, 1], [1, 1, 1]]

- Suppose you want to create a 2d list with coordinates as its values.

```
x = [[(i,j) for j in range(3)] for i in range(3)]
```

[[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)]]

- If we want to create a 2d list with 0 as its value:

```
x = [[0 for j in range(3)] for i in range(3)]
```

Output-

[ [0, 0, 0], [0, 0, 0], [0, 0, 0] ]

## How to Retrieve values from a python 2d list

A 2d list can be accessed by two attributes namely row and columns and to access these list we use the following code-

```
for i in range(len(rows)):
for j in range(len(columns)):
print(rows[i][j],end="")
print("\n")
```

Output:

1 1 1 1 1 1 1 1 1

We can also use the concept of slicing for retrieving the data from whichever rows and columns we want.

Suppose that we only want to retrieve row 1 and 2 and all the columns, for this purpose we can use slicing.

```
list1 = [ [1,2,3], [4,5,6], [7,8,9], [10,11,12] ]
print(list1[1:3][:]) """ [1:3] is used for rows-1,2[:] is used to represent all values"""
```

Output:

[[4, 5, 6], [7, 8, 9]]

Now, let suppose we want to retrieve all the rows but only column 1:

```
print(list1[:][1])
```

Output-

[4,5,6]

But this is not columns 1. Why? It’s because it is the limitation of a python 2d list that we cannot perform column-wise operations on a 2d list. For that purpose, we have a NumPy array.

## Limitations of 2d list

As seen in the last example we cannot perform the column-wise operation in a 2d list. For this purpose, we have to use a 2d NumPy array. To convert a 2d list into a 2d array we first have to import the NumPy library using pip install NumPy and then do the following operations:

```
list_2d=[[1,2,3] ,[4,5,6] ,[7,8,9],[10,11,12]]
import numpy #importing numpy library
arr_2d=numpy.array(list_2d) #array function converts list into array
print(type(list1))
print(type(arr_2d))
```

Output –

<class 'list'> <class 'numpy.ndarray'>

And now if we try the same way to find the 1st column of all the rows we are getting the correct answer with the 2d array.

```
print(list_2d[:][1]) # Incorrect Output- [4, 5, 6]
print(arr_2d[:,1]) # Correct Output -[ 2 5 8 11]
```

## Advantages of using 2d list:

We cannot simply use a 1d list for every purpose. Suppose we have data of different items purchased by different customers and we want to store those items in a list.

One way to do that is:

```
customer_1=["rice”, ”cumin seeds”, ”wheat”]
customer_2=["detergent”, ”soap”, ”shampoo”]
customer_3=["bread”, ”eggs”, ”salt”]
```

But let suppose we have 1000 customers or maybe more, will it be the right way, to make 1000 different lists?

But if we use 2d array to represent the items, it would be a lot better, cleaner approach, and a faster one too.

```
items=[ ["rice”,”cumin seeds”,”wheat”] , ["detergent”,”soap”,”shampoo”] , ["bread”,”eggs”,”salt”] ]
```

Also, it would be very easy to retrieve the values from the list. We will learn how to retrieve values from a 2d list in python.

## How to apply some common methods on 2d python list:

- append(): append() is quite a common function used on a list. It is used to add value at the last of the list.

If we want to add a new list at the end of the old list,

```
list_2d= [[1,2,3] ,[4,5,6],[7,8,9],[10,11,12]]
list_2d.append([5,6,7])
print(list_2d)
```

OUTPUT:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [5,6,7,]]

If we want to add an element at the last of a sub-list:

```
print(list_2d[0].append(5))
```

Output-

[[1, 2, 3 ,5], [4, 5, 6], [7, 8, 9], [10, 11, 12], [5,6,7,]]

- sort(): If we want to arrange them in ascending or descending order we use sort().

Now lets see what happens when we apply sort() on a 2d list.

```
list_2d=[[7, 8, 9],[ 11,10, 12], [4, 5, 6], [1, 2, 3]]
list_2d.sort()
list_2d # By default it gives output in ascending order
```

OUTPUT:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [11, 10, 12]]

Observe that in the output only the list as a whole is sorted and not the sub list.

If we want to sort both sub-list and the outer list, we can use the following code,

```
list_2d=[[7, 8, 9],[ 11,10, 12], [4, 5, 6], [1, 2, 3]]
for i in range(len(list_2d)):
list_2d[i].sort() #sorting the sublist
list_2d.sort()
print(list_2d)
```

OUTPUT-

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

- Flattening the 2d list: When we convert a 2d list into a 1d list, the process is known as flattening. In python so many methods and libraries can help us in achieving the goal, we can also first convert the 2d list into a 2d array and then apply flat() on the array. But as we are in the learning phase we will use the naïve approach to achieve the same.

```
list_2d=[[7, 8, 9],[11,10, 12],[4, 5, 6],[1, 2, 3]]
list1=[]
for i in range(len(list_2d)):
for j in range(len(list_2d[i])):
list1.append(list_2d[i][j])
```

OUTPUT-

[7, 8, 9, 11, 10, 12, 4, 5, 6, 1, 2, 3]

## Must Read:

- How to Convert String to Lowercase in
- How to Calculate Square Root
- User Input | Input () Function | Keyboard Input
- Best Book to Learn Python

### Conclusion

**Python 2d list** has a lot of advantages and limitations too. We should always know when to use it. We should know when to use dictionaries, NumPy array, python 1d list.

Try to run the programs on your side and let me know if you have any queries.

*Happy Coding!*