Tuple
Tuple
Tuple
• Similar to a list except it is immutable.
• Syntactically, it is comma-seperated list of values.
– tuple = 'a', 'b', 'c', 'd', 'e‘
• To create a tuple with a single element, we have to include the comma:
– t1 = ('a',)
– type(t1)
<type 'tuple'>
• Without the comma, Python treats ('a') as a string in parentheses:
– t2 = ('a')
– type(t2) ??
• The operations on tuples are the same as the operations on lists
• The index operator selects an element from a tuple.
– tuple = ('a', 'b', 'c', 'd', 'e')
– tuple[0]
– 'a‘
• The slice operator selects a range of elements.
– tuple[1:3]
– ('b', 'c‘)
• But if we try to modify one of the elements of the tuple, we get an error.
– tuple[0] = 'A'
– TypeError: object doesn't support item assignment
Example
• a and x are aliases for the same value. Changing x inside swap makes x refer
to a different value, but it has no effect on a in main . Similarly, changing y
has no effect on b.
Random Numbers
#for float
import random
for x in range(5):
print(random.random())
#choice based
import random
t1 = 1, 2, 3, 4, 5, 6,44444444,66,7
print(random.choice(t1))
List of Random Numbers(float)
randomList(8)
0.15156642489
0.498048560109
0.810894847068
0.360371157682
0.275119183077
0.328578797631
0.759199803101
0.800367163582
Counting
• Divide the problem into sub problems and look for sub problems that fit a computational
pattern
• Traverse a list of numbers and count the number of times a value falls in a given range.
• Eg:
def inBucket(t, low, high):
count = 0
for num in t:
if low < num < high:
count = count + 1
return count
This development plan is known as pattern matching.
Many Buckets