Python Essentials 3



Arrays in Python


Python doesn't have a native Array data structure, but it uses the List as a multidimensional Array. Arrays and Lists are both used in Python to store data, but they don't serve exactly the same purposes. While they both can be indexed and iterated through, but the main difference between a List and an Array is the functions that we can perform to them. For example, you can divide an Array by 3, and each number in the array will get divided by 3. Whereas in a List we can't do so and division by 3 in List will throw an error.

Array of items are restricted by the TypeCode, and can be initialized by an optional initializer values. The image below shows the array TypeCodes:


Some example of Array DataTypes, Array creation, and operations in Array are shown below:

# Array DataType
import array as ar
vals = ar.array('i', [5,9,-8,4,2])
print(vals)


import array as ar
vals = ar.array('I', [5,9,8,4,2])
print(vals)


import array as ar
vals = ar.array('f', [5,9,8,4,2])
print(vals)


import array as ar
vals = ar.array('i', [5,9,-8,4,2])
print(vals.buffer_info())


import array as ar
vals = ar.array('i', [5,9,-8,4,2])
print(vals.typecode)


import array as ar
vals = ar.array('i', [5,9,-8,4,2])
vals.reverse()
print(vals)


import array as ar
vals = ar.array('i', [5,9,-8,4,2])
vals.reverse()
print(vals[0])


import array as ar
vals = ar.array('i', [5,9,-8,4,2])
for i in range(5):
    print(vals[i])


import array as ar
vals = ar.array('i', [5,9,-8,4,2])
for i in range(len(vals)):
    print(vals[i])


import array as ar
vals = ar.array('i', [5,9,-8,4,2])
for x in vals:
    print(x)


# Create new Array
import array as ar
vals = ar.array('i', [5,9,8,4,2])
# From old array create a new array
# And we don't know the DataType and size of the old array

newArr = ar.array(vals.typecode, (a for a in vals))
for x in newArr:
    print(x)


import array as ar
vals = ar.array('i', [5,9,8,4,2])
# From old array create a new array
# And we don't know the DataType and size of the old array

newArr = ar.array(vals.typecode, (a*a for a in vals))
for x in newArr:
    print(x)


# Same code using a while loop
import array as ar
vals = ar.array('i', [5,9,8,4,2])
newArr = ar.array(vals.typecode, (a*a for a in vals))
i=0
while i<len(newArr):
    print(newArr[i])
    i+=1


Array values from User, Search in Array

# Create a blank Array and ask user to enter values
from array import *
arr = array('i',[])
n = int(input("Enter the length of the array: "))
for i in range(n):
    x = int(input("Enter the next value: "))
    arr.append(x)
print(arr)


Result:
Enter the length of the array: 5
Enter the next value: 23
Enter the next value: -12
Enter the next value: 43
Enter the next value: 35
Enter the next value: -10
array('i', [23, -12, 43, 35, -10])


# Create a blank Array and ask user to enter values
from array import *
arr = array('i',[])
n = int(input("Enter the length of the array: "))
for i in range(n):
    x = int(input("Enter the next value: "))
    arr.append(x)
print(arr)
# Ask user to search a value in the array
val = int(input("Enter the value for search: "))
k=0
for e in arr:
    if e==val:
        print(Index number of', val, 'is ', k)
        break
    k+=1


Or you can use a method:
print('Index number of', val, 'is', arr.index(val))

Result:
Enter the length of the array: 5
Enter the next value: 3
Enter the next value: 6
Enter the next value: 4
Enter the next value: 2
Enter the next value: -7
array('i', [3, 6, 4, 2, -7])
Enter the value for search: 2
Index number of 2 is 3



Working with NumPy in Python


Why NumPy
As mentioned above, Python doesn't have a native Array data structure, but it uses the List as a multidimensional Array. Up till now we have worked with one-dimensional Array, that is basically a List only. In order to work with two- or three- dimensional Array we need a third-party library call NumPy, which adds support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.

To install NumPy for IDLE, go to command prompt and type “pip3 install numpy”, as shown below:
And then we import NumPy as "import numpy"

To install NumPy for PyCharm:

Go to File > Settings > Project <Project Name>
       Click on Project Interpreter
       Click on the “+” button on the top right corner of the right panel
       Search for “numpy”, select “numpy” from the list
Click “Install Package” button in the button.

See the following screens for reference.

# Create Array using NumPy
from numpy import *
arr = array([12,43,25,37,11,28])
print('Array is', arr)


Result:
Array is [12 43 25 37 11 28]

Note: No need to specify Data Type in the Array. But if you want to specify, do that at the end, e.g.:

from numpy import *
arr = array([12,43,25,37,11,28], int)
print('Array is', arr)

Six Ways of Creating Arrays in NumPy:

  1. array( )
  2. linspace( )
  3. logspace( )
  4. arrange( )
  5. zeros( )
  6. ones( )
1. Using Array()

from numpy import *
arr = array([12,43,25,37,11,28])
print('Array DataType is:', arr.dtype)
print('Array is:', arr)

Result:
Array DataType is: int32
Array is: [12 43 25 37 11 28]

from numpy import *
arr = array([12,43,25,37,11,28], float)
print('Array DataType is:', arr.dtype)
print('Array is:', arr)

Result:
Array DataType is: float64
Array is: [12. 43. 25. 37. 11. 28.]

from numpy import *
arr = array([12,43,25,37,11,28.0])
print('Array DataType is:', arr.dtype)
print('Array is:', arr)

Result:
Array DataType is: float64
Array is: [12. 43. 25. 37. 11. 28.]

2. Using linspace( )

from numpy import *
arr = linspace(0,15,16)  # Linspace 0=start, 15=stop, 16=parts
print('Array DataType is:', arr.dtype)
print('Array is:', arr)

Result:
Array DataType is: float64
Array is: [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15.]

from numpy import *
arr = linspace(0,15,20)  # 0=start, 15=stop, 20=parts
print('Array DataType is:', arr.dtype)
print('Array is:', arr)

Result:
Array DataType is: float64
Array is: [ 0.          0.78947368  1.57894737  2.36842105  3.15789474  3.94736842
  4.73684211  5.52631579  6.31578947  7.10526316  7.89473684  8.68421053
  9.47368421 10.26315789 11.05263158 11.84210526 12.63157895 13.42105263
 14.21052632 15.        ]

from numpy import *
arr = linspace(0,15)  # without mentioning parts
print('Array DataType is:', arr.dtype)
print('Array is:', arr)

Result:
Array DataType is: float64
Array is: [ 0.          0.30612245  0.6122449   0.91836735  1.2244898   1.53061224
  1.83673469  2.14285714  2.44897959  2.75510204  3.06122449  3.36734694
  3.67346939  3.97959184  4.28571429  4.59183673  4.89795918  5.20408163
  5.51020408  5.81632653  6.12244898  6.42857143  6.73469388  7.04081633
  7.34693878  7.65306122  7.95918367  8.26530612  8.57142857  8.87755102
  9.18367347  9.48979592  9.79591837 10.10204082 10.40816327 10.71428571
 11.02040816 11.32653061 11.63265306 11.93877551 12.24489796 12.55102041
 12.85714286 13.16326531 13.46938776 13.7755102  14.08163265 14.3877551
 14.69387755 15.        ]

3. Using logspace( )

from numpy import *
arr = logspace(1,40,5)  # Logspace. Spacing based on log
print(arr)

Result:
[1.00000000e+01 5.62341325e+10 3.16227766e+20 1.77827941e+30
 1.00000000e+40]

from numpy import *
arr = logspace(1,40,5)  # Logspace. Spacing based on log
print('%.2f' %arr[0])
print('%.2f' %arr[1])
print('%.2f' %arr[2])
print('%.2f' %arr[3])
print('%.2f' %arr[4])

Result:
10.00
56234132519.03
316227766016837943296.00
1778279410038922838185969975296.00
10000000000000000303786028427003666890752.00

4. Using arrange( )

from numpy import *
arr = arange(0,15,2)  # It is A-Range. 0=start, 15=end, 2=steps
print('Array DataType is:', arr.dtype)
print('Array is:', arr)

Result:
Array DataType is: int32
Array is: [ 0  2  4  6  8 10 12 14]

5. Using zeros( )

from numpy import *
arr = zeros(5) # Zeros
print(arr)

Result:
[0. 0. 0. 0. 0.]

6. Using ones( )

from numpy import *
arr = ones(5)  # Ones
print(arr)

Result:
[1. 1. 1. 1. 1.]

from numpy import *
arr = ones(5, int)  # Ones
print(arr)

Result:
[1 1 1 1 1]

Operations in Array using NumPy


# Operations with Array using NumPy
from numpy import *
arr = array([1,2,3,4,5])
arr = arr + 5
print(arr)

Result:
[ 6  7  8  9 10]

from numpy import *
arr1 = array([1,2,3,4,5])
arr2 = array([6,7,8,9,10])
arr = arr1 + arr2
print(arr)

Result:
[ 7  9 11 13 15]

from numpy import *
arr1 = array([1,2,3,4,5])
print(sin(arr1))

Result:
[ 0.84147098  0.90929743  0.14112001 -0.7568025  -0.95892427]

from numpy import *
arr1 = array([1,2,3,4,5])
print(log(arr1))

Result:
[0.         0.69314718 1.09861229 1.38629436 1.60943791]

from numpy import *
arr1 = array([1,2,3,4,5])
print(sum(arr1))
print(min(arr1))
print(max(arr1))

Result:
15
1
5


from numpy import *
arr1 = array([1,2,3,4,5])
arr2 = array([6,7,8,9,10])
print(concatenate([arr1,arr2]))  # Concatenate two arrays


Result:
[ 1  2  3  4  5  6  7  8  9 10]

from numpy import *
arr1 = array([2,6,8,1,3])
arr2 = arr1  # Simple array copying
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))


Result:
[2 6 8 1 3]
[2 6 8 1 3]
2396099461488
2396099461488


Note: Both Arrays have the same address

from numpy import *
arr1 = array([2,6,8,1,3])
arr2 = 2*arr1
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))


Result:
[2 6 8 1 3]
[ 4 12 16  2  6]
1682295767408
1682297033712


from numpy import *
arr1 = array([2,6,8,1,3])
arr2 = arr1.view()  # Copy an array to a different address
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))


Result:
[2 6 8 1 3]
[2 6 8 1 3]
2456238178672
2456238379056


Note: Both Arrays have the different address

from numpy import *
arr1 = array([2,6,8,1,3])
arr2 = arr1.view()  # Shallow copy
arr1[1] = 70
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))


Result:
[ 2 70  8  1  3]
[ 2 70  8  1  3]
2831262826864
2831264010288


from numpy import *
arr1 = array([2,6,8,1,3])
arr2 = arr1.copy()  # Deep copy
arr1[1] = 70
print(arr1)
print(arr2)
print(id(arr1))
print(id(arr2))



Result:
[ 2 70  8  1  3]
[2 6 8 1 3]
2199916724592
2199917908016


Working with Matrix


# Working with Array using NumPy
from numpy import *
arr1 = array([
                [1,2,3],
                [4,5,6]
            ])
print(arr1)
print('DataType of array is: ',arr1.dtype)  # DataType of array
print('Dimension of array is: ',arr1.ndim)  # Dimension of array
print('Shape of array is: ',arr1.shape)  # Shape of array
print('Size of array is: ',arr1.size)  # Size of array


Result:
[[1 2 3]
 [4 5 6]]
DataType of array is:  int32
Dimension of array is:  2
Shape of array is:  (2, 3)
Size of array is:  6


from numpy import *
arr1 = array([
                [1,2,3],
                [4,5,6]
            ])
arr2 = arr1.flatten()  # 2D to 1D array
print('Main array is:')
print(arr1)
print('Flattened array is: ',arr2)


Result:
Main array is:
[[1 2 3]
 [4 5 6]]
Flattened array is:  [1 2 3 4 5 6]


from numpy import *
arr1 = array([
                [1,2,3,4,5,6],
                [4,5,6,7,8,9]
            ])
arr2 = arr1.flatten()  # 2D to 1D array
arr3 = arr2.reshape(3,4)  # 1D to 2D array
print('Main array is:')
print(arr1)
print('Flattened array is: ',arr2)
print('Reshaped array is:')
print(arr3)


Result:
Main array is:
[[1 2 3 4 5 6]
 [4 5 6 7 8 9]]
Flattened array is:  [1 2 3 4 5 6 4 5 6 7 8 9]
Reshaped array is:
[[1 2 3 4]
 [5 6 4 5]
 [6 7 8 9]]


from numpy import *
arr1 = array([
                [1,2,3,4,5,6],
                [4,5,6,7,8,9]
            ])
arr2 = arr1.flatten()  # 2D to 1D array
arr3 = arr2.reshape(2,2,3)  # Two 2D arrays
print('Main array is:')
print(arr1)
print('Flattened array is: ',arr2)
print('Reshaped array is:')
print(arr3)


Result:
Main array is:
[[1 2 3 4 5 6]
 [4 5 6 7 8 9]]
Flattened array is:  [1 2 3 4 5 6 4 5 6 7 8 9]
Reshaped array is:
[[[1 2 3]
  [4 5 6]]

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


# Working with Matrix using NumPy
from numpy import *
arr1 = array([
                [1,2,3,4],
                [4,5,6,7]
            ])
m = matrix(arr1*2)  # Converting array to matrix
print('Main matrix is:')
print(arr1)
print('New matrix is:')
print(m)


Result:
Main matrix is:
[[1 2 3 4]
 [4 5 6 7]]
New matrix is:
[[ 2  4  6  8]
 [ 8 10 12 14]]


from numpy import *
m = matrix('1 2 3 4;5 6 7 8')  # Creating a matrix
print('Matrix is:')
print(m)


Result:
Matrix is:
[[1 2 3 4]
 [5 6 7 8]]


from numpy import *
from numpy import *
m = matrix('1 2 3; 4 5 6; 7 8 9')  # Creating a matrix
print('Matrix is:')
print(m)
print('Diagonal elements are:')
print(diagonal(m))
print('Min value is: ', m.min())
print('Max value is: ', m.max())


Result:
Matrix is:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Diagonal elements are:
[1 5 9]
Min value is:  1
Max value is:  9


# Operations with Matrix using NumPy
from numpy import *
m1 = matrix('1 2 3; 4 5 6; 7 8 9')
m2 = matrix('9 8 7; 6 5 4; 3 2 1')
m3 = m1+m2
m4 = m1*m2
print('Matrix 1 is:')
print(m1)
print('Matrix 2 is:')
print(m2)
print('Sum of matrices is:')
print(m3)
print('Product of matrices is:')
print(m4)


Result:
Matrix 1 is:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Matrix 2 is:
[[9 8 7]
 [6 5 4]
 [3 2 1]]
Sum of matrices is:
[[10 10 10]
 [10 10 10]
 [10 10 10]]
Product of matrices is:
[[ 30  24  18]
 [ 84  69  54]
 [138 114  90]]




Reference: Taking online class from Navin Reddy's Python YouTube Videos