**NumPy**

*chevron_left*

**Cookbooks**

# Difference between Python List and Numpy array

*schedule*Aug 11, 2023

*toc*Table of Contents

*expand_more*

**mathematics behind data science**with 100+ top-tier guides

Start your free 7-days trial now!

There are 2 major benefits of Numpy arrays over Python lists:

Broadcasting: when you need to perform calculations over all the items in an array / list

Indexing: when you have a 2D list /array, it is easier and more efficient to retrieve a single column using arrays

# Broadcasting

For example, say we need to divide all student raw scores in a test by `2`

to arrive at the final score. If we try to perform the following using a Python list:

```
raw_scores = [50, 60, 70]final_scores = raw_scores / 2final_scores
TypeError: unsupported operand type(s) for /: 'list' and 'int'
```

We get a `TypeError`

as such operations are not supported by Python lists.

Instead using a Numpy Array:

```
raw_scores = np.array([50, 60, 70])final_scores = raw_scores / 2final_scores
array([25., 30., 35.])
```

As we can see, each element in the array has been divided by `2`

.

All elements in an array have to be of the same data type. (Not the case for Python list, which can handle elements of different types).

# Indexing

To retrieve first column of 2D Numpy Array:

```
numpy_2d_array = np.array([[1,2,3], [4,5,6]])numpy_2d_array[:, 0]
array([1, 4])
```

To retrieve first column of 2D list we must use list comprehension:

```
list2d = [[1,2,3], [4,5,6]][row[0] for row in list2d ]
[1, 4]
```