Wednesday, March 6, 2024

Numpy Array vs Python List

 import numpy as np

list = [1,2,'Heaven','Hell']
arr = np.array(list)
#Please note, generally numpy generally does not contain Strings. It is mainly used
for numerical Operration.


list[2:] = 3
This is not allowed for normal python list. This will throw an error like
below:
    list[2:] = 3
TypeError: can only assign an iterable

However, it is allowed for numpy array and it will change the
original numpy array.

import numpy as np
list = [1,2,'Heaven','Hell']
arr = np.array(list)
arr[2:] = 3
print(arr)

Ouput: ['1' '2' '3' '3']

Now, no avoid changing the original array, we can use copy option as below.

Without copy:
import numpy as np
list = [1,2,'Heaven','Hell']
arr = np.array(list)
arr_copy =arr
arr_copy[2:] = 3
print(arr)
print(arr_copy)

O/p:
['1' '2' '3' '3']
['1' '2' '3' '3']

With copy:
import numpy as np
list = [1,2,'Heaven','Hell']
arr = np.array(list)
arr_copy =arr.copy()
arr_copy[2:] = 3
print(arr)
print(arr_copy)
O/p:
['1' '2' 'Heaven' 'Hell']
['1' '2' '3' '3']


list_one = [1,2,3]
list_two = [4,5,6]
print(f"Result of list addition: {list_one + list_two}")
arr_one = np.array(list_one)
arr_two = np.array(list_two)
print(f"Result of array addition: {arr_one + arr_two}")

O/p:
Result of list addition: [1, 2, 3, 4, 5, 6]
Result of array addition: [5 7 9]



No comments:

Post a Comment