Previous Lecture Lecture 7 Next Lecture

Lecture 7, Tue 01/30

Strings, Tuples, Namedtuples

Recorded Lecture: 1_30_24

not in operator

evenNumbers = [2, "4", 6, "8", 6]
D = { 1234567:'A+', 7654321:'A-', 5555555:'B+' }
s = "CMPSCW8"

print("4" not in evenNumbers) #False
print(4 not in evenNumbers) #True
print(7654321 not in D) #False
print(9999999 not in D) #True
print("SCW" not in s) #False
print("CS" not in s) #True
print(3 not in [1, 2, 3]) #False
print(5 not in [1, 2, 3]) #True

Strings

s = "CMPSW8"
print(s[0])
print(s[3])
s[5] = "9" # error
s = "CMPSW9" # Ok

Tuples

x = (1,3,5,7)
print(x)
print(type(x))
print(x[2])
x[2] = 15 # error
x = (1,3,5,7)
print(x)
print(type(x))
print(x[2])
x = (1, 3, 15, 7) # replace value with new object
print(x)

Namedtuples

# Step 1: Allow your program to use namedtuples.
# Note: collections is a module that contains functionality for
# collection types, including namedtuples.
# Here we are simply using the namedtuple in this entire collection
from collections import namedtuple

# Step 2: Design what your object looks like
Student = namedtuple("Student", ["name", "ID", "major", "GPA"])
# Parameters of function, 1st is name of the namedTuple type – Student
# 2nd is a list containing the names of the attributes.

# Step 3: Create distinct student objects
# s1 and s2 refer to INSTANCES of Student namedtuples (each have their
# own values)
s1 = Student("John Doe", 12345678, "MUSIC", 3.5)
s2 = Student("Jane Doe", 87654321, "CS", 3.7)

# Step 4: Refer to specific fields within these namedtuples with '.'
print("Name of s1: ", s1.name)
print("ID of s1: ", s1.ID)
print("Major of s1: ", s1.major)
print("GPA of s1: ", s1.GPA)
print("Name of s2: ", s2.name)
print("ID of s2: ", s2.ID)
print("Major of s2: ", s2.major)
print("GPA of s2: ", s2.GPA)
print(s1.GPA)
s1.GPA = s1.GPA + 0.1 # error
s1 = Student(s1.name, s1.ID, s1.major, s1.GPA + 0.1) # OK
print(s1.GPA)

A brief note about import vs. from

import math # gives us access to functionality in the math library
print(math.sqrt(4)) # how to use a math library function.

# "from" Example:
from math import sqrt
print(sqrt(4)) # no need to use "math." when calling sqrt function