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

Python Review

This document provides a summary of Python collections like lists, tuples, dictionaries, and NumPy arrays. It discusses how to create, access, modify, and iterate over each collection type. It also covers NumPy array operations like shape, max, dot product, and matrix multiplication. Precautions are mentioned around representing vectors and matrices as NumPy arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python Review

This document provides a summary of Python collections like lists, tuples, dictionaries, and NumPy arrays. It discusses how to create, access, modify, and iterate over each collection type. It also covers NumPy array operations like shape, max, dot product, and matrix multiplication. Precautions are mentioned around representing vectors and matrices as NumPy arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

30-09-2023

Basic of Python
• Collections
• List
Python Review • Tuple
A quick refresher • Set
• Dictionary
• NumPy (Matrix)

Collections - List Collections - List


• Concatenate two lists
• Lists are mutable arrays. Let's see how they work. • += operator is a short hand for list1 = list1 + list2 (can also be used
• names = ["Zach", "Jay"] for -, *, / and on other types of variables)
• names += ["Abi", "Kevin"]
• Index into list by index • print(names)
• print(names[0])
• Two ways to create an empty list
• Append to list (appends to end of list) • more_names = []
• names.append("Richard") • more_names = list()
• print(names)
• Create a list that contains different data types, this is allowed in
• Get length of list Python
• print(len(names)) • stuff = [1, ["hi", "bye"], -0.12, None]
• print(stuff)

1
30-09-2023

Collections - List Collections - List


• List slicing is a useful way to access a slice of elements • : takes the slice of all elements along a dimension, is
in a list. very useful when working with numpy arrays
• numbers = [0, 1, 2, 3, 4, 5, 6]
• print(numbers[:])
• Slices from start index (inclusive) to end index
(exclusive) • # Negative index wraps around, start counting from
• print(numbers[0:3]) the end of list
• When start index is not specified, it is start of list • print(numbers[-1])
• When end index is not specified, it is end of list • print(numbers[-3:])
• print(numbers[:3]) • print(numbers[3:-2])
• print(numbers[5:])

Collections - Tuples Collections - Tuple


• Tuples are immutable arrays. Let's see how they work.
• But unlike lists, tuples do not support item re-assignment
• Use parentheses for tuples, square brackets for lists • names[0] = "Richard"
• names = ("Zach", "Jay") • Create an empty tuple
• Syntax for accessing an element and getting length are • empty = tuple()
the same as lists • print(empty)
• print(names[0]) • Create a tuple with a single item, the comma is important
• print(len(names)) • single = (10,)
• print(single)

2
30-09-2023

Collections - Dictionaries Collections - Dictionaries


• Check if a key is in the dictionary
Dictionaries are hash maps. Let's see how they work.
• print("Zach" in phonebook)
• Two ways to create an empty dictionary
• phonebook = {}
• print("Kevin" in phonebook)
• phonebook = dict() • Get corresponding value for a key
• Create dictionary with one item • print(phonebook["Jay"])
• phonebook = {"Zach": "12-37"} • Delete an item
• Add another item • del phonebook["Zach"]
• phonebook["Jay"] = "34-23" • print(phonebook)

Loops
• #Basic for loop
Loops
• for i in range(5): • Second Method
print(i) • for i, name in enumerate(names):
• To iterate over a list
• names = ["Zach", "Jay", "Richard"] print(i, name)
• for name in names: • To iterate over a dictionary
print(name) • phonebook = {"Zach": "12-37", "Jay": "34-23"}
• To iterate over indices and values in a list
• # Way 1 • Iterate over keys
• for i in range(len(names)): • for name in phonebook:
• print(i, names[i]) print(name)
• print("---")
print("---")

3
30-09-2023

Loops NumPy – Numerical computation


• Iterate over values •Import numpy
•for number in phonebook.values(): •import numpy as np
print(number) •Create numpy arrays from lists
print("---") •x = np.array([1,2,3])
• Iterate over keys and values •a = np.array([[1,2,3]])
•for name, number in phonebook.items(): •y = np.array([[3,4,5]])
print(name, number) •z = np.array([[6,7],[8,9]])

Precautions!!
NumPy – Array Dimensions - Shape • Vectors can be represented as 1-D arrays of shape (N,) or 2-D
arrays of shape (N, 1) or (1, N).
•print(x.shape) • (N,), (N, 1), and (1,N) are not the same.
•print(y.shape) • Matrices are generally represented as 2-D arrays of shape (M, N).
• Test the shape before you go further down with the program
•print() • a = np.arange(10)
•print(z) • b = a.reshape((5, 2))
• print(a)
•print(z.shape) • print()
• print(b)

4
30-09-2023

NP Array Operations NP Matrix Operations


• A = np.array([[1, 2], [3, 4]])
• x = np.array([[1,2],[3,4], [5, 6]]) • B = np.array([[3, 3], [3, 3]])
• print(x) • print(A)
• print() • print(B)
• print("---")
• print(x.shape)
• print(A * B)
• print(np.max(x, axis = 1)) We can do matrix multiplication with np.matmul or @.
• print(np.max(x, axis = 1).shape) • One way to do matrix multiplication
• print(np.matmul(A, B))
• print(np.max(x, axis = 1, keepdims = True))
• Another way to do matrix multiplication
• print(np.max(x, axis = 1, keepdims = • print(A @ B)
True).shape)

NP Matrix Operations NP Matrix Operations


• u = np.array([1, 2, 3]) • This works.
• v = np.array([1, 10, 100]) • print(np.dot(v, W))
• print(np.dot(u, v)) • print(np.dot(v, W).shape)
• Can also call numpy operations on the numpy array, useful for
chaining together multiple operations • This does not. Why?
• print(u.dot(v)) • print(np.dot(W, v))

• W = np.array([[1, 2], [3, 4], [5, 6]]) • We can fix the above issue by transposing W.
• print(v.shape) • print(np.dot(W.T, v))
• print(W.shape) • print(np.dot(W.T, v).shape)

5
30-09-2023

Indexing in matrix
• x = np.random.random((3, 4))
• Selects all of x
• print(x[:])
• Selects the 0th and 2nd rows
• print(x[np.array([0, 2]), :])
• Selects 1st row as 1-D vector and and 1st through 2nd elements
• print(x[1, 1:3])

• Boolean indexing
• print(x[x > 0.5])
• 3-D vector of shape (3, 4, 1)
• print(x[:, :, np.newaxis])

You might also like