MS1008-Tutorial 6
MS1008-Tutorial 6
MS1008-Tutorial 6
MS1008
Week 6
Three Common Data Structures in Python
Lists
A List is an ordered sequence of items.
Result:
Lists are mutable:
newList [0] = [1,2,3] or newList[:2] = [27] or newList[:2] = 27
print(newList) error?
Lists vs Strings
Lists: Similarities with Strings
Program: Program:
Result:
Result:
Example:
Tuples
Expendable!
Dictionary
In data structure terms, a dictionary is better termed as an associative
array, or associative list, or a map.
Dictionaries are collections but they are not sequences like lists,
strings, or tuples.
• There is no order to the elements of a dictionary.
• In fact, the order (for example, when printed) might change as
elements are added or deleted.
Key:Value
You can think of it as a list of pairs.
- The key, which is the first element of the pair, is used to
retrieve the second element, which is the value.
Just like a dictionary, you look up a word by its spelling to find the
associated definition.
3. Tuples are immutable. Yet, we can modify the tuple in the list L = [1, (2, 3),
4] to L = [1, (5, 6), 4]. Why?
Ans: The tuple (2, 3) in the list is an object on its own. When we change
the tuple in the list, we are not changing the contents of the tuple but rather
replacing it with a new object which is a different tuple (5, 6). Because lists
are mutable, we can change its elements.
Problem 2
Ans:
v1 = (1, 2, 3) # define two vectors with arbitrary values
v2 = (6, 7, 8)
v3 = (v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2])
print("The sum of the vectors: ", v3)
dot = v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
print("The dot product is: ", dot)
Problem 3
Solution to Problem 3
# Read in a date string dd/mm/yyyy. Split into 3 bits and store in date list
date = input("Enter date string dd/mm/yyyy: ").split("/")
if len(date) != 3:
print("Wrong date format")
elif date[0].isdigit() and int(date[0]) >0 and int(date[0])<32 :
if date[1].isdigit() and int(date[1]) >0 and int(date[1])<13:
if date[2].isdigit():
# right format
print("The long date is {} {}, {}". format(date[0], \
month[int(date[1])], date[2]))
else:
print("Wrong year format")
else:
print("Wrong month format")
else:
print("Wrong day format")