Where NumPy differs from straight Python

In this tutorial, we will learn where NumPy differs from straight Python operations with the help of examples? By Pranit Sharma Last updated : April 25, 2023

What we can perform in NumPy is indirectly what we are performing in Python. However, without NumPy, there are certain things that are not possible or if possible, it is time costly.

There are many operations where NumPy differs from straight Python. We are discussing some of them.

1. Every standard operator is overloaded to distribute across the array

A point of surprise is that almost every standard operator is overloaded to distribute across the array.

For example, define a list and an array

Example 1

# Import numpy
import numpy as np

# Creating a list
l = [1,2,3,4,5,6,7,8,9,10]

# Display list
print("List:\n",l)

# Can be overloaded to numpy array
arr = np.array(l)

# Display array
print("Array:\n",l)

Output

List:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2. Multiplication Operation in Straight Python Vs. NumPy

Now, if we perform multiplication operation, it is different in straight Python and NumPy.

Example 2

# Import numpy
import numpy as np

# Creating a list
l = [1,2,3,4,5,6,7,8,9,10]

# Display list
print("List:\n",l)

# Can be overloaded to numpy array
arr = np.array(l)

# Display array
print("Array:\n",l)
print()

# Operation on Straight Python
print("Result(l*2): ",l*2,"\n")

# Operation on NumPy
print("Result(arr*2): ",arr*2,"\n")

Output

List:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Result(l*2):  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

Result(arr*2):  [ 2  4  6  8 10 12 14 16 18 20] 

3. Addition Operation in Straight Python Vs. NumPy

It can be better understood, when we perform an addition operation where the list does not support addition unlike to NumPy array.

Example 3

# Import numpy
import numpy as np

# Creating a list
l = [1,2,3,4,5,6,7,8,9,10]

# Display list
print("List:\n",l)

# Can be overloaded to numpy array
arr = np.array(l)

# Display array
print("Array:\n",l)
print()

# Operation on NumPy
print("Result(arr+2): ",arr+2,"\n")

# Operation on Straight Python
print("Result(l+2): ",l+2,"\n")

Output

List:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Result(arr+2):  [ 3  4  5  6  7  8  9 10 11 12] 

Traceback (most recent call last):
  File "/home/main.py", line 21, in <module>
    print("Result(l+2): ",l+2,"\n")
TypeError: can only concatenate list (not "int") to list

Conclusion

In the above example, we discussed some of the points. But, there are many more types of operations in NumPy that differ from straight Python operations.

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.