0% found this document useful (0 votes)
50 views

Python Day 5 Arrays

The document discusses arrays in Python and compares lists and the array module. It provides 3 key points: 1) Lists are more flexible than arrays as they can store elements of different data types, while arrays require all elements to be of the same type. However, lists are faster than arrays. 2) The array module can be used to create arrays that enforce element type consistency, but NumPy is generally preferred for mathematical computations on arrays due to its powerful N-dimensional arrays. 3) NumPy arrays provide multidimensional arrays of numbers and allow for common matrix operations like addition, multiplication, and transpose through its dot method and transpose function, making tasks simpler compared to nested lists.

Uploaded by

PriyaGandhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Python Day 5 Arrays

The document discusses arrays in Python and compares lists and the array module. It provides 3 key points: 1) Lists are more flexible than arrays as they can store elements of different data types, while arrays require all elements to be of the same type. However, lists are faster than arrays. 2) The array module can be used to create arrays that enforce element type consistency, but NumPy is generally preferred for mathematical computations on arrays due to its powerful N-dimensional arrays. 3) NumPy arrays provide multidimensional arrays of numbers and allow for common matrix operations like addition, multiplication, and transpose through its dot method and transpose function, making tasks simpler compared to nested lists.

Uploaded by

PriyaGandhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Array

Python Lists Vs array Module as Arrays


We can treat lists as arrays. However, we cannot constrain the type of elements stored
in a list. For example:

a = [1, 3.5, "Hello"]

If you create arrays using array module, all elements of the array must be of the same
numeric type.

import array as arr

a = arr.array('d', [1, 3.5, "Hello"]) // Error

How to create arrays?


As you might have guessed from the above example, we need to import array module
to create arrays. For example:

import array as arr


a = arr.array('d', [1.1, 3.5, 4.5])
print(a)

Here, we created an array of float type. The letter 'd' is a type code. This determines
the type of the array during creation.

Commonly used type codes:


Type
C Type Python Type Minimum size in bytes
code

'b' signed char int 1

'B' unsigned char int 1

'u' Py_UNICODE Unicode character 2

'h' signed short int 2

unsigned
'H' int 2
short

'i' signed int int 2

'I' unsigned int int 2

'l' signed long int 4

'L' unsigned long int 4

'f' float float 4

'd' double float 8

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:

import array as arr


a = arr.array('i', [2, 4, 6, 8])

print("First element:", a[0])


print("Second element:", a[1])
print("Second last element:", a[-1])

Arrays are used to store multiple values in one single variable:

Example
Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

Remember, index starts from 0 (not 1) similar like lists.

How to slice arrays?


We can access a range of items in an array by using the slicing operator :.

import array as arr

numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]


numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th


print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:]) # 6th to end
print(numbers_array[:]) # beginning to end

When you run the program, the output will be:

array('i', [62, 5, 42])

array('i', [2, 5, 62])

array('i', [52, 48, 5])

array('i', [2, 5, 62, 5, 42, 52, 48, 5])

How to change or add elements?


Arrays are mutable; their elements can be changed in a similar way like lists.

import array as arr

numbers = arr.array('i', [1, 2, 3, 5, 7, 10])

# changing first element


numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# changing 3rd to 5th element
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

We can add one item to a list using append() method or add several items


using extend()method.

import array as arr

numbers = arr.array('i', [1, 2, 3])

numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])

# extend() appends iterable to the end of the array


numbers.extend([5, 6, 7])
print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])

We can concatenate two arrays using + operator.

import array as arr

odd = arr.array('i', [1, 3, 5])


even = arr.array('i', [2, 4, 6])

numbers = arr.array('i') # creating empty array of integer


numbers = odd + even

print(numbers)
How to remove/delete elements?
We can delete one or more items from an array using Python's del statement.

import array as arr

number = arr.array('i', [1, 2, 3, 3, 4])

del number[2] # removing third element


print(number) # Output: array('i', [1, 2, 3, 4])

del number # deleting entire array


print(number) # Error: array is not defined

We can use the remove() method to remove the given item, and pop() method to


remove an item at the given index.

import array as arr

numbers = arr.array('i', [10, 11, 12, 12, 13])

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.

Be sure to learn about Python lists before proceed this article.

Let's see how to work with a nested list.

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

column = []; # empty list


for row in A:
column.append(row[2])

print("3rd column =", column)

When we run the program, the output will be:

A = [[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]


A[1] = [-5, 8, 9, 0]

A[1][2] = 9

A[0][-1] = 12

3rd column = [5, 9, 11]

Here are few more examples related to Python matrices using nested lists.

 Add two matrices


 Transpose a Matrix
 Multiply two matrices

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,

 Visit: How to install NumPy?


 If you are on Windows, download and install anaconda distribution of Python. It comes
with NumPy and other several packages related to data science and machine learning.

Once NumPy is installed, you can import and use it.

NumPy provides multidimensional array of numbers (which is actually an object). Let's


take an example:

import numpy as np
a = np.array([1, 2, 3])
print(a) # Output: [1, 2, 3]
print(type(a)) # Output: <class 'numpy.ndarray'>

As you can see, NumPy's array class is called ndarray.

How to create a NumPy array?


There are several ways to create NumPy arrays.

1. Array of integers, floats and complex Numbers

import numpy as np

A = np.array([[1, 2, 3], [3, 4, 5]])


print(A)

A = np.array([[1.1, 2, 3], [3, 4, 5]]) # Array of floats


print(A)

A = np.array([[1, 2, 3], [3, 4, 5]], dtype = complex) # Array of complex


numbers
print(A)

When you run the program, the output will be:

[[1 2 3]

[3 4 5]]
[[1.1 2. 3. ]

[3. 4. 5. ]]

[[1.+0.j 2.+0.j 3.+0.j]

[3.+0.j 4.+0.j 5.+0.j]]

2. Array of zeros and ones

import numpy as np

zeors_array = np.zeros( (2, 3) )


print(zeors_array)

'''
Output:
[[0. 0. 0.]
[0. 0. 0.]]
'''

ones_array = np.ones( (1, 5), dtype=np.int32 ) // specifying dtype


print(ones_array) # Output: [[1 1 1 1 1]]

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]]
'''

Learn more about other ways of creating a NumPy array.

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.

Addition of Two Matrices

We use + operator to add corresponding elements of two NumPy matrices.


import numpy as np

A = np.array([[2, 4], [5, -6]])


B = np.array([[9, -3], [3, 6]])
C = A + B # element wise addition
print(C)

'''
Output:
[[11 1]
[ 8 0]]
'''

Multiplication of Two Matrices

To multiply two matrices, we use dot() method. Learn more about


how numpy.dot works.

Note: * is used for array multiplication (multiplication of corresponding elements of two


arrays) not matrix multiplication.

import numpy as np

A = np.array([[3, 6, 7], [5, -3, 0]])


B = np.array([[1, 1], [2, 1], [3, -3]])
C = a.dot(B)
print(C)

'''
Output:
[[ 36 -12]
[ -1 2]]
'''

Transpose of a Matrix

We use numpy.transpose to compute transpose of a matrix.

import numpy as np

A = np.array([[1, 1], [2, 1], [3, -3]])


print(A.transpose())

'''
Output:
[[ 1 2 3]
[ 1 1 -3]]
'''

As you can see, NumPy made our task much easier.

Access matrix elements, rows and columns


Access matrix elements

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])

print("A[0] =", A[0]) # First element


print("A[2] =", A[2]) # Third element
print("A[-1] =", A[-1]) # Last element

When you run the program, the output will be:

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]])

# First element of first row


print("A[0][0] =", A[0][0])

# Third element of second row


print("A[1][2] =", A[1][2])

# Last element of last row


print("A[-1][-1] =", A[-1][-1])

When we run the program, the output will be:

A[0][0] = 1

A[1][2] = 9

A[-1][-1] = 19

Access rows of a Matrix

import numpy as np

A = np.array([[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]])

print("A[0] =", A[0]) # First Row


print("A[2] =", A[2]) # Third Row
print("A[-1] =", A[-1]) # Last Row (3rd row in this case)

When we run the program, the output will be:

A[0] = [1, 4, 5, 12]

A[2] = [-6, 7, 11, 19]


A[-1] = [-6, 7, 11, 19]

Access columns of a Matrix

import numpy as np

A = np.array([[1, 4, 5, 12],
[-5, 8, 9, 0],
[-6, 7, 11, 19]])

print("A[:,0] =",A[:,0]) # First Column


print("A[:,3] =", A[:,3]) # Fourth Column
print("A[:,-1] =", A[:,-1]) # Last Column (4th column in this case)

When we run the program, the output will be:

A[:,0] = [ 1 -5 -6]

A[:,3] = [12 0 19]

A[:,-1] = [12 0 19]

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.

Let's take an example:

import numpy as np
letters = np.array([1, 3, 5, 7, 9, 7, 5])

# 3rd to 5th elements


print(letters[2:5]) # Output: [5, 7, 9]

# 1st to 4th elements


print(letters[:-5]) # Output: [1, 3]

# 6th to last elements


print(letters[5:]) # Output:[7, 5]

# 1st to last elements


print(letters[:]) # Output:[1, 3, 5, 7, 9, 7, 5]

# reversing a list
print(letters[::-1]) # Output:[5, 7, 9, 7, 5, 3, 1]

Now, let's see how we can slice a matrix.

import numpy as np

A = np.array([[1, 4, 5, 12, 14],


[-5, 8, 9, 0, 17],
[-6, 7, 11, 19, 21]])
print(A[:2, :4]) # two rows, four columns

''' Output:
[[ 1 4 5 12]
[-5 8 9 0]]
'''

print(A[:1,]) # first row, all columns

''' Output:
[[ 1 4 5 12 14]]
'''

print(A[:,2]) # all rows, second column

''' Output:
[ 5 9 11]
'''

print(A[:, 2:5]) # all rows, third to fifth column

'''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?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an
index number.

Access the Elements of an Array


You refer to an array element by referring to the 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"

The Length of an Array


Use the len() method to return the length of an array (the number of elements in an array).

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.

Looping Array Elements


You can use the for in loop to loop through all the elements of an array.

Example
Print each item in the cars array:

for x in cars:
  print(x)

Adding Array Elements


You can use the append() method to add an element to an array.

Example
Add one more element to the cars array:

cars.append("Honda")

Removing Array Elements


You can use the pop() method to remove an element from the array.

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")

Note: The remove() method only removes the first occurrence of the specified value.

Array Methods
Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elem

ents with the specified value

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove( Removes the first item with the specified value


)

reverse() Reverses the order of the list

sort() Sorts the list

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

You might also like