You are on page 1of 43

Tuples

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

• we can't modify the elements of a tuple, we can replace it with a


different tuple:
– tuple = ('a', 'b', 'c', 'd', 'e')
– tuple = ('A',) + tuple[1:]
– tuple
– ('A', 'b', 'c', 'd', 'e')
Tuple Assignment

• Tuple assignment allows the assignment of values to a tuple of


variables on the left side of the assignment from the tuple of values
on the right side of the assignment.
• E.g.
Anil=('1','Anil','kumar')
(id, f_name , lst_name ) = Anil
>>>print(id)
1
Tuple Assignmnt
• To swap the values, using conventional assignment statements, we have
to use the assignment statement with a temporary variable.
– temp = a
– a=b
– b = temp
• Python provides a form of tuple assignment that solves this problem
neatly:
– a, b = b, a
• The number of variables on the left and the number of values on the
right have to be the same.
Tuples as Return Values

• Functions can return tuples as return values.


• For example:
– def swap(x, y):
return y, x
• Then we can assign the return value to a tuple with two variables:
– a, b = swap(a, b)
def swap(x, y): # incorrect version
x, y = y, x
• If we call this function like this:
swap(a, b)

• a and x are aliases for the same value. Changing x inside swap makes x refer
to a different value which is x= value of y, but it has no effect on a in main .
Similarly, changing y has no effect on b in main.
• E.g
>>>def div_mod(a,b):
quotient=a/b
remainder=a%b
return quotient, remainder
>>>x=10
>>>y=3
>>>t=div_mod(x,y)
>>>print t # will get (3,1) as output
>>>type(t) #type will be tuple
Unpack a list1 using
*
• list11 = ["This" , "is", "a", "Python",
"program"]
• list12 = [10, 9,5,3,10]
• x=[*list11 , *list12 ]
– #use comma to merge, * to
unpack
• print(x)
Use input() and get few elements. Now treat them
as a list and tuple and set
• tup = tuple(input("enter tuple"))
• print(tup)
Basic Tuple Operations

• Concatenation: works in the same way as it does in lists. ‘+’ operator


is used for concatenation.
• Repetition: It is performed by ‘*’ operator. E.g: (‘Hello’,)*4
• In Operator: It tells user that the given element exists in the tuple or
not. It gives a Boolean output. E.g.
>>>Tuple=(’10’,’20’,’30’)
>>>20 in tuple
True
Built-in Tuple Operations
• len(tuple): returns the length of a tuple
• min(tuple): returns smallest value among all the elements
• max(tuple): returns largest value among all the elements
• cmp(tuple1, tuple2): compares items of two tuples. Doesnt work in python 3. so
use ==
• tuple(seq): converts a list into a tuple
• zip(tuple1,tuple2): it zips elements from two tuples into a list of tuples.
e.g.
Consider the tuple (1,2,3,4,5,6,7,8,9,10).
Write a program to print half its values in one line and the other half in
the next line.
• tup = (1,2,3,4,5,6,7,8,9,10) tup = (1,2,3,4,5,6,7,8,9,10)
• lst1,lst2 = [],[] for i in range(0,5):
print(tup[i],end = ' ')
• for i in range(0,5): print()
for i in range(5,10):
• lst1.append(tup[i])
print(tup[i],end = ' ')
• for i in range(5,10):
• lst2.append(tup[i])
• print(lst1)
tp = (1,2,3,4,5,6,7,8,9,10)
• print(lst2) tp1 = tp[:5]
• o/p: tp2 = tp[5:]
print (tp1)
• [1, 2, 3, 4, 5] print (tp2)
• [6, 7, 8, 9, 10]
Consider the tuple(12,7,38,56,78,47,88,79,23). WAP to print another
tuple whose values are even numbers in the given tuple
• tup = (12,7,38,56,78,47,88,79,23)

• print("\nThe Even Numbers in this Tuple are:")


• for i in tup:
• if(i % 2 == 0):
• print(i, end = " ")
Define a function that prints a tuple whose values are the cube of a
number between 1 and 15(both included).
• Input: list = [4, 1, 6, 2]
• Output:
• [(4, 64), (1, 1), (6, 216), (2, 8)]
Random Numbers

• The random module contains a function called random that returns a


floating point number between 0.0 and 1.0.
Use randint()

• import random
• print(random.randint(0, 10))
• choice() is an inbuilt function in Python programming language that
returns a random item from a list, tuple, or string.

• Python offers a function that can generate random numbers from a


specified range and also allowing rooms for steps to be included,
called randrange() in random module.
• random ( ) inbuilt function
• Example: Printing a random value from a list / tuple
• import random
• t1 = 1, 2, 3, 4, 5, 6,44444444,66,7

• print(random. choice(t1))
• print(random.randint(7, 99999999999999999))

• print(random. randint(t1)) #not correct


• o/p:
• 4
Use of sort() and sorted()
• sort() returns nothing and so do changes in original sequence like
list.sort() or tuple.sort() is correct but sort(list) or sort(tuple) is
incorrect
• Sorted() do sorting and then returns it as a sorted sequence
• Let L is a list =[1, 3, 4, 2]

• L.sort() #correct
• L.sort(reverse = True) #correct but L.sorted() is incorrect

• >>>sorted(L)) #or use as


sorted(L,reverse=True)
Consider the tuple (1,2,3,4,5,6,7,8,9,10). Write a program to print half its
values in one line and the other half in the next line.
• tup = (1,2,3,4,5,6,7,8,9,10)
tup = (1,2,3,4,5,6,7,8,9,10)
• lst1,lst2 = [],[] for i in range(0,5):
• for i in range(0,5): print(tup[i],end = ' ')
print()
• lst1.append(tup[i]) for i in range(5,10):
print(tup[i],end = ' ')
• for i in range(5,10):
• lst2.append(tup[i])
• print(lst1)
• print(lst2) tp = (1,2,3,4,5,6,7,8,9,10)
tp1 = tp[:5]
• o/p: tp2 = tp[5:]
• [1, 2, 3, 4, 5] print (tp1)
print (tp2)
• [6, 7, 8, 9, 10]
Consider the tuple(12,7,38,56,78,47,88,79,23). WAP to print another
tuple whose values are even numbers in the given tuple
• tup = (12,7,38,56,78,47,88,79,23)
• print("\nThe Even Numbers in this Tuple are:")
• for i in tup:
• if(i % 2 == 0):
• print(i, end = " ")
Practice questions

• Consider the tuple (1,2,3,4,5,6,7,8,9,10). Write a program to print half its values in
one line and the other half in the next line.
• Consider the tuple(12,7,38,56,78,47,88,79,23). WAP to print another tuple whose
values are even numbers in the given tuple.
• An email address is provided: hello@python.org. Using tuple assignment, split the
username and domain from the email address. (Use split method).
• Define a function that prints a tuple whose values are the cube of a number
between 1 and 15(both included).
Questions

• Q1. Create a tuple and try to changing value of any one element, also display the length of list.
• Q2. Create a tuple having single element and append two tuples.
• Q3. Create a tuple and sort it.
• Q4. Create a tuple of numbers and print sum of all the elements.
• Q5. Program to compare elements of tuples.
• Q6. Program to find maximum and minimum of tuple.
• Q7. Count the occurrence of element in tuple in a specific range.
• Q8. Reverse a tuple.
• Q9.Write a loop that traverses the previous tuple and prints the length of each element. What happens if you send
an floating number in index?
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
– low = inBucket(a, 0.0, 0.5)
– high = inBucket(a, 0.5, 1)

This development plan is known as pattern matching.


Many Buckets

• With two buckets, range will be:


– low = inBucket(a, 0.0, 0.5)
– high = inBucket(a, 0.5, 1)
• But with four buckets it is:
– bucket1 = inBucket(a, 0.0, 0.25)
– bucket2 = inBucket(a, 0.25, 0.5)
– bucket3 = inBucket(a, 0.5, 0.75)
– bucket4 = inBucket(a, 0.75, 1.0)
• If the number of buckets is numBuckets, then the width of each
bucket is 1.0 / numBuckets.
numBuckets = 8
buckets = [0] * numBuckets
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
buckets[i] = inBucket(t, low, high)
print buckets

You might also like