Previous Lecture Lecture 2 Next Lecture

Lecture 2, Thu 04/06

Python Review cont.

Recorded Lecture:

Python Lists

Example

>>> x = []
>>> len(x)  # returns number of elements in list
>>> x.append(1)	 # adds to the end of the list
>>> x
[1]
>>> len(x)
1
>>> x = [1,2,2,3,3,3]
>>> len(x)
6
>>> x[3]  # extracts an element at an index (index starts at 0)
3
>>> x[3] = "3"  # assigns a value at a certain index
>>> x
[1, 2, 2, '3', 3, 3]
>>> x = [1,1,2,2,2]
>>> x.count(2)  # counts the number of times 2 appears in the list
3
>>> x.count(3)
0
>>> x = [1,'2',3,'4']
>>> '1' in x  # Returns True if '1' is in the list, False otherwise
False
>>> 1 in x
True
>>> x.insert(2, 2.5)  # inserts 2.5 in index 2 of the list, shifts right elements over
>>> x
[1, '2', 2.5, 3, '4']
>>> x.pop()  # removes and returns last element of list
'4'
>>> x
[1, '2', 2.5, 3]
>>> x.pop(1)  # removes element at index 1
'2'
>>> x
[1, 2.5, 3]
>>> del x[1]  # Notice that there isn’t any output, but still removes element
>>> x
[1, 3]

List Slicing

Example

>>> x[1:4]
[2, 3, 4]
>>> x[1:7]
[2, 3, 4, 5]
>>> x[1:]
[2, 3, 4, 5]
>>> x[:3]
[1, 2, 3]

Strings

Example

>>> x = "CS9"
>>> type(x[2])
<class 'str'>
>>> x[2]
'9'

But…

>>> x[2] = "1"
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    x[2] = "1"
TypeError: 'str' object does not support item assignment

Some useful string methods

>>> x = x.replace("9", "1")  #returns a string,replaces the “9” with “1” in x
>>> x
'CS1'
>>> x.split("S")  # splits the string at the first occurrence of “S”
['C', '1']
>>> x.find("1")  # returns the index of the first occurrence of “1”
2

Functions

# Function definition
def double(n):
    ''' Returns 2 times the parameter ''' # Good to comment functions!
    return 2 * n

Mutable vs. Immutable

Example

def changeListParameter(x):
    x[0] = "!"
    return x

a = ["C","S","9"]
print(changeListParameter(a))  # ['!', 'S', '9']
print(a)  # ['!', 'S', '9']

def changeStringParameter(x):
    x = x.replace("C", "!")
    return x

b = "CS9"
print(changeStringParameter(b))  # !S9
print(b)  # CS9 - b didn't change!

Control Structures

if statements

if BOOLEAN_EXPRESSION:
	STATEMENT(s)

if/else statements

if BOOLEAN_EXPRESSION:
	STATEMENT(s) #1
else:
	STATEMENT(s) #2

elif statements

x = False
if x:
    print("Shouldn't print")
elif 4 < 5:
    print("4 < 5")
else:
    print("Shouldn't print")

While Loops

while BOOLEAN_EXPRESSION:
    STATEMENT(S)
while True:
    print("Weee!!!")  # Will always execute since BOOLEAN_EXPRESSION == True

For loops

for VARIABLE in COLLECTION:
	STATEMENT(s)
for x in range(4):
	print(x, "Hello!" * x)
	print("---")

Sets

Common set operators

s2 = set([2,4,6])		
print(s2)
print(type(s2))
print(3 in s2)
print("?" in s2)
print(5 not in s2) # True
print(len(s2))

# Combine values from two sets
s3 = set([4,5,6])
combined_set = s2 | s3
print(combined_set)

# Get the common elements from two sets
intersecting_set = s2 & s3
print(intersecting_set)

Dictionaries

DICT = {<key1>:<value1>, <key2>:<value2>, ... , <keyN>:<valueN>}

D = {} # Empty dictionary. Notice the curly braces instead of []
print(D)
print(len(D))

D = {'Jane':18, 'Jen':19, 'Joe':20, 'John':21}

print(D)
print(len(D))
print("Jane's age is:", D['Jane'])

# Simple way to get key / value
for x in D:
    print(x) # Prints the key
    print(D[x]) # Prints the value

Restrictions on using Dictionaries

value = D.pop("Joe")  # returns the value associated with Joe, error if doesn’t exist
print(value)
print(D)
value = D.get("jksldf") # returns none if doesn’t exist
print(value)

D["Jem"] = 22 # Adds element to dictionary
print(D)