Python Day 5 Arrays
Python Day 5 Arrays
If you create arrays using array module, all elements of the array must be of the same
numeric type.
Here, we created an array of float type. The letter 'd' is a type code. This determines
the type of the array during creation.
unsigned
'H' int 2
short
We will not discuss about different C types in this article. We will use two type codes in
this entire article: 'i' for integers and 'd' for floats.
Note: The 'u' type code for Unicode characters is deprecated since version 3.3. Avoid
using it when possible.
How to access array elements?
We use indices to access elements of an array:
Example
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])
print(numbers)
How to remove/delete elements?
We can delete one or more items from an array using Python's del statement.
numbers.remove(12)
print(numbers) # Output: array('i', [10, 11, 12, 13])
print(numbers.pop(2)) # Output: 12
print(numbers) # Output: array('i', [10, 11, 13])
Check this page to learn more about Python array and array methods:
When to use arrays?
Lists are much more flexible than arrays. They can store elements of different data
types including string. Also, lists are faster than arrays. And, if you need to do
mathematical computation on arrays and matrices, you are much better off using
something like NumPylibrary.
Unless you don't really need arrays (array module may be needed to interface with C
code), don't use them.
A matrix is a two-dimensional data structure where numbers are arranged into rows and
columns. For example:
This matrix is a 3x4 (pronounced "three by four") matrix because it has 3 rows and 4
columns.
Python Matrix
Python doesn't have a built-in type for matrices. However, we can treat list of a list as a
matrix. For example:
A = [[1, 4, 5],
[-5, 8, 9]]
We can treat this list of a list as a matrix having 2 rows and 3 columns.
A = [[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]]
print("A =", A)
print("A[1] =", A[1]) # 2nd row
print("A[1][2] =", A[1][2]) # 3rd element of 2nd row
print("A[0][-1] =", A[0][-1]) # Last element of 1st Row
A[1][2] = 9
A[0][-1] = 12
Here are few more examples related to Python matrices using nested lists.
Using nested lists as a matrix works for simple computational tasks, however, there is a
better way of working with matrices in Python using NumPy package.
NumPy Array
NumPy is a package for scientific computing which has support for a powerful N-
dimensional array object. Before you can use NumPy, you need to install it. For more
info,
import numpy as np
a = np.array([1, 2, 3])
print(a) # Output: [1, 2, 3]
print(type(a)) # Output: <class 'numpy.ndarray'>
import numpy as np
[[1 2 3]
[3 4 5]]
[[1.1 2. 3. ]
[3. 4. 5. ]]
import numpy as np
'''
Output:
[[0. 0. 0.]
[0. 0. 0.]]
'''
Here, we have specified dtype to 32 bits (4 bytes). Hence, this array can take values
from -2 to 2 -1.
-31 -31
3. Using arange() and shape()
import numpy as np
A = np.arange(4)
print('A =', A)
B = np.arange(12).reshape(2, 6)
print('B =', B)
'''
Output:
A = [0 1 2 3]
B = [[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
'''
Matrix Operations
Above, we gave you 3 examples: addition of two matrices, multiplication of two matrices
and transpose of a matrix. We used nested lists before to write those programs. Let's
see how we can do the same task using NumPy array.
'''
Output:
[[11 1]
[ 8 0]]
'''
import numpy as np
'''
Output:
[[ 36 -12]
[ -1 2]]
'''
Transpose of a Matrix
import numpy as np
'''
Output:
[[ 1 2 3]
[ 1 1 -3]]
'''
Similar like lists, we can access matrix elements using index. Let's start with a one-
dimensional NumPy array.
import numpy as np
A = np.array([2, 4, 6, 8, 10])
A[0] = 2
A[2] = 6
A[-1] = 10
Now, let's see how we can access elements of a two-dimensional array (which is
basically a matrix).
import numpy as np
A = np.array([[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]])
A[0][0] = 1
A[1][2] = 9
A[-1][-1] = 19
import numpy as np
A = np.array([[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]])
import numpy as np
A = np.array([[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]])
A[:,0] = [ 1 -5 -6]
If you don't know how this above code works, read slicing of a matrix section of this
article.
Slicing of a Matrix
Slicing of a one-dimensional NumPy array is similar to a list. If you don't know how
slicing for a list works, visit Understanding Python's slice notation.
import numpy as np
letters = np.array([1, 3, 5, 7, 9, 7, 5])
# reversing a list
print(letters[::-1]) # Output:[5, 7, 9, 7, 5, 3, 1]
import numpy as np
''' Output:
[[ 1 4 5 12]
[-5 8 9 0]]
'''
''' Output:
[[ 1 4 5 12 14]]
'''
''' Output:
[ 5 9 11]
'''
'''Output:
[[ 5 12 14]
[ 9 0 17]
[11 19 21]]
'''
As you can see, using NumPy (instead of nested lists) makes it a lot easier to work with
matrices, and we haven't even scratched the basics. We suggest you to explore NumPy
package in detail especially if you trying to use Python for data science/analytics.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could
look like this:
car1 = "Ford";
car2 = "Volvo";
car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not
3 cars, but 300?
An array can hold many values under a single name, and you can access the values by referring to an
index number.
Example
Get the value of the first array item:
x = cars[0]
Example
Modify the value of the first array item:
cars[0] = "Toyota"
Example
Return the number of elements in the cars array:
x = len(cars)
Note: The length of an array is always one more than the highest array index.
Example
Print each item in the cars array:
for x in cars:
print(x)
Example
Add one more element to the cars array:
cars.append("Honda")
Example
Delete the second element of the cars array:
cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example
Delete the element that has the value "Volvo":
cars.remove("Volvo")
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.