Harold Nelson
4/3/2018
## Warning: package 'reticulate' was built under R version 3.4.4
For this material we will be following Chapter 10 of the Python for Everybody text by Charles Severance. A pdf of the text is posted in Moodle.
A tuple is a sequence of values separated by commas. A tuple may or may not be enclosed in parentheses.
Here are some examples.
## (1, 2, 3)
## (1, 2, 3)
Note that in both cases print() enclosed the tuples in parentheses.
Doodle Create your own simple exercise to demonstrate the contents of this slide.
Values of tuple components may be extracted by numerical index in the same way as lists or strings. Slicing also works in exactly the same way.
Examples
## 1
## 3
Doodle Create your own simple exercise to demonstrate the contents of this slide.
The same concatenation and repetitin we used with strings works with tuples.
Examples
## (1, 2, 3, 'a', 'b', 'c')
## (1, 2, 3, 1, 2, 3, 'a', 'b', 'c')
## (1, 2, 3, 'a', 'b', 'c', 1, 2, 3, 'a', 'b', 'c')
Doodle Create your own simple exercise to demonstrate the contents of this slide.
Example
The following line of code will fail. Try it in idle or cocalc.
## 1
Doodle Create your own simple exercise to demonstrate the contents of this slide.
A tuple may contain items of any type. If an item in a tuple is mutable. The mutable item may be changed and this will be reflected in the tuple.
Example
## ([1, 2, 3], [4, 5, 6])
## ([1, 2, 3, 'a'], [4, 5, 6])
Doodle Create your own simple exercise to demonstrate the contents of this slide.
A tuple may be converted to another data structure containing the same data. Lists have many methods that can alter them and sets are useful for unduplication
Example
## [1, 2, 3]
## {1, 2, 3}
Doodle Create your own simple exercise to demonstrate the contents of this slide.
Multiple assignment is a valuable coding technique which allows us to extract the values in a tuple and assign them to specific variables. There must be exacly the same number of variables as values in the tuple.
Example
## (1, 2, 3)
## 1
## 2
## 3
Doodle Create your own simple exercise to demonstrate the contents of this slide.
def findExtremeDivisors(n1, n2):
minVal, maxVal = None, None
for i in range(2, min(n1, n2) + 1):
if n1%i == 0 and n2%i == 0:
if minVal == None or i < minVal:
minVal = i
if maxVal == None or i > maxVal:
maxVal = i
return (minVal, maxVal)
lcd, gcd = findExtremeDivisors(27,18)
print(lcd)
## 3
## 9
Tuples may be compared. Equality requires that both tuples have the same values in the same places. Comparison starts on the left and continues until a tie-breaker is found.
Examples
## False
## False
## True
Doodle Create your own simple exercise to demonstrate the contents of this slide.