Tuple in Python
Tuple in Python
Tuples consists of a number of values separated by comma and enclosed within parentheses. Tuple is similar to list, values in a list can be changed but not in a tuple.
The term Tuple is originated from the Latin word represents an abstraction of the sequence of numbers:
single(1), double(2), triple(3), quadruple(4), quintuple(5), sextuple(6), septuple(7), octuple(8), ..., n‑tuple, ...,
Advantages of Tuples over list
1. The elements of a list are changeable (mutable) whereas the elements of a tuple are unchangeable (immutable), this is the key difference between tuples and list.
2. The elements of a list are enclosed within square brackets. But, the elements of a tuple are enclosed by paranthesis.
3. Iterating tuples is faster than list.
Creating Tuples
Creating tuples is similar to list. In a list, elements are defined within square brackets, whereas in tuples, they may be enclosed by parenthesis. The elements of a tuple can be even defined without parenthesis. Whether the elements defined within parenthesis or without parenthesis, there is no differente in it's function.
Syntax:
# Empty tuple
Tuple_Name = ( )
# Tuple with n number elements
Tuple_Name = (E1, E2, E2 ……. En)
# Elements of a tuple without parenthesis
Tuple_Name = E1, E2, E3 ….. En
Example
>>> MyTup1 = (23, 56, 89, 'A', 'E', 'I', "Tamil")
>>> print(MyTup1)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
>>> MyTup2 = 23, 56, 89, 'A', 'E', 'I', "Tamil"
>>> print (MyTup2)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
(i) Creating tuples using tuple( ) function
The tuple( ) function is used to create Tuples from a list. When you create a tuple, from a list, the elements should be enclosed within square brackets.
Syntax:
Tuple_Name = tuple( [list elements] )
Example
>>> MyTup3 = tuple( [23, 45, 90] )
>>> print(MyTup3)
(23, 45, 90)
>>> type (MyTup3)
<class ‘tuple’>
(ii) Creating Single element tuple
While creating a tuple with a single element, add a comma at the end of the element. In the absence of a comma, Python will consider the element as an ordinary data type; not a tuple. Creating a Tuple with one element is called “Singleton” tuple.
Example
>>> MyTup4 = (10)
>>> type(MyTup4)
<class 'int'>
>>> MyTup5 = (10,)
>>> type(MyTup5)
<class 'tuple'>
Accessing values in a Tuple
Like list, each element of tuple has an index number starting from zero. The elements of a tuple can be easily accessed by using index number.
Example
>>> Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48)
# to access all the elements of a tuple
>>> print(Tup1)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
#accessing selected elements using indices
>>> print(Tup1[2:5])
(91, 'Tamil', 'Telugu')
#accessing from the first element up to the specified index value
>>> print(Tup1[:5])
(12, 78, 91, 'Tamil', 'Telugu')
# accessing from the specified element up to the last element.
>>> print(Tup1[4:])
('Telugu', 3.14, 69.48)
# accessing from the first element to the last element
>>> print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
Update and Delete Tuple
As you know a tuple is immutable, the elements in a tuple cannot be changed. Instead of altering values in a tuple, joining two tuples or deleting the entire tuple is possible.
Example
# Program to join two tuples
Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)
Output
(2, 4, 6, 8, 10, 1, 3, 5, 7, 9)
To delete an entire tuple, the del command can be used.
Syntax:
del tuple_name
Example
Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ", Tup1)
del Tup1
print (Tup1)
Output:
The elements of Tup1 is (2, 4, 6, 8, 10)
Traceback (most recent call last):
File "D:/Python/Tuple Examp 1.py", line 4, in <module>
print (Tup1)
NameError: name 'Tup1' is not defined
Tuple Assignment
Tuple assignment is a powerful feature in Python. It allows a tuple variable on the left of the assignment operator to be assigned to the values on the right side of the assignment operator. Each value is assigned to its respective variable.
Example
>>> (a, b, c) = (34, 90, 76)
>>> print(a,b,c)
34 90 76
# expression are evaluated before assignment
>>> (x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
>>> print(x,y,z,p)
4 5.666666666666667 1 False
Note that, when you assign values to a tuple, ensure that the number of values on both sides of the assignment operator are same; otherwise, an error is generated by Python.
Returning multiple values in Tuples
A function can return only one value at a time, but Python returns more than one value from a function. Python groups multiple values and returns them together.
Example : Program to return the maximum as well as minimum values in a list
def Min_Max(n):
a = max(n)
b = min(n)
return(a, b)
Num = (12, 65, 84, 1, 18, 85, 99)
(Max_Num, Min_Num) = Min_Max(Num)
print("Maximum value = ", Max_Num)
print("Minimum value = ", Min_Num)
Output:
Maximum value = 99
Minimum value = 1
Nested Tuples
In Python, a tuple can be defined inside another tuple; called Nested tuple. In a nested tuple, each tuple is considered as an element. The for loop will be useful to access all the elements in a nested tuple.
Example
Toppers = (("Vinodini", "XII-F", 98.7), ("Soundarya", "XII-H", 97.5),
("Tharani", "XII-F", 95.3), ("Saisri", "XII-G", 93.8))
for i in Toppers:
print(i)
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
Qus What do you understand by mutability?
Ans: Mutable means changeable. In Python, mutable types are those whose values can be changed in place. Only three types are mutable in python – Lists, Dictionaries and Sets.
Qus Start with the list[8,9,10]. Do the following using list functions
(a) Set the second entry (index 1) to 17
(b) Add 4, 5 and 6 to the end of the list.
(c) Remove the first entry from the list.
(d) Sort the list.
(e) Double the list.
(f) Insert 25 at index 3
Ans:
(a) list[1]=17
(b) list.append(4)
list.append(5)
list.append(6)
(c) list.pop(0)
(d) list.sort()
(e) list=list*2
(f) list.insert(3,25)
Qus. If a is [1, 2, 3], what is the difference (if any) between a*3 and [a, a, a]?
Ans: a*3 will produce [1,2,3,1,2,3,1,2,3], means a list of integers and [a, a, a] will produce [[1,2,3],[1,2,3],[1,2,3]], means list of lists
Qus. If a is [1, 2, 3], is a *3 equivalent to a + a + a?
Ans: Yes, Both a*3 and a+a+a will produce same result.
Qus. If a is [1, 2, 3], what is the meaning of a [1:1] = 9?
Ans: This will generate an error "TypeError: can only assign an iterable'.
Qus If a is [1, 2, 3], what is the meaning of a [1:2] = 4 and a [1:1] = 4?
Ans: These will generate an error "TypeError: can only assign an iterable".
Qus. What are list slices?
Ans: List slices are the sub-part of a list extracted out. You can use indexes of the list elements to create list slices as per following format. Syntax is as follows –
Qus Does a slice operator always produce a new list?
Ans: Yes, this will create a new list.
Qus. How are lists different from strings when both are sequences?
Ans: Lists are similar to strings in many ways like indexing, slicing, and accessing individual elements but they are different in the sense that
(i) Lists are mutable while strings are immutable.
(ii) In consecutive locations, strings store the individual characters while list stores the references of its elements.
(iii) Strings store single type of elements-all characters while lists can store elements belonging to different types.
Qus. What are nested Lists?
Ans: A list can have an element in it, which itself is a list. Such a list is called nested list. e.g.
L = [1,2,3,4,[5,6,7],8]
Qus. Discuss the utility and significance of Lists.
Ans: The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. List is majorly used with dictionaries when there is large number of data.
Qus What is the purpose of the del operator and pop method? Try deleting a slice.
Ans: del operator is used to remove an individual item, or to remove all items identified by a slice. It is to be used as per syntax given below –
>>>del List[index]
>>>del List[start:stop]
pop method is used to remove single element, not list slices. The pop() method removes an individual item and returns it. Its syntax is –
>>>a=List.pop() #this will remove last item and deleted item will be assigned to a.
>>>a=List[10] # this will remove the ite at index 10 and deleted item will be assigned to a.
Qus. What are list slices?
Ans: List slices, like string slices are the sub part of a list extracted out. Indexes can be used to create list slices as per following format:
seq = L[start:stop]
Qus. What do you understand by true copy of a list? How is it different from shallow copy?
Ans: A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won‘t create copies of the child objects themselves.
True Copy means you can create a copy of a list using New_list=My_list. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.
Qus What do you understand by immutability?
Ans: Immutability means not changeable. The immutable types are those that can never change their value in place. In python following types are immutable –
I. Integers
II. Floating point numbers
III. Booleans
IV. Strings
V. Tuples
Qus How are Tuples different from Lists when both are sequences?
Ans: Tuples are similar to lists in many ways like indexing, slicing, and accessing individual values but they are different in the sense that –
Tuples are immutable while lists are mutable.
List can grow or shrink while tuples cannot.
Qus Can tuples be nested?
Ans: Yes, tuples can be nested. e.g (1,2,3,(4,5,6))
Qus. Discuss the utility and significance of Tuples.
Ans: Tuples are great for holding static data that you don't plan on modifying and changing a lot. Tuples are four to seven times faster than lists. This means for every list item manipulated, four to seven tuples could be manipulated within that time frame. This has huge advantages for scientific work, as this allows for speedy data reading.
Qus. How can you say that a tuple is an ordered list of objects?
Ans: A tuple is an ordered list of objects. This is evidenced by the fact that the objects can be accessed through the use of an ordinal index amd for a given index, same element is returned every time.
Qus. Why can‟t List can be used as keys?
Ans: List is mutable datatype. And Keys of dictionary must be immutable type. This is the region that list cannot be used as keys.
Qus. What type of objects can be used as keys in dictionary?
Ans: Any immutable objects can be used as keys in dictionary.
Qus. Can you change the order of the dictionaries contents?
Ans: Yes, the order of dictionary contents may be changed.
Qus. Can you modify the keys in a dictionary?
Ans: Keys cannot be modified in dictionary while values are mutable in dictionary.
Qus. Can you modify the value in a dictionary?
Ans: Yes, Values can be modified in dictionaries.
Qus. Is dictionary Mutable? Why?
Ans: Dictionary is mutable type because we can change its values.
Qus How are dictionaries different from Lists?
Ans: The dictionary is similar to lists in the sense that it is also a collection of data-items but it is different from lists in the sense that lists are sequential collections(ordered) and dictionaries are non-sequential collections(unordered).
Elements in lists or tuples can be accessed by using indexes. But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list.
Qus. When are dictionaries more useful than lists?
Ans: Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.
Qus. Discuss the utility and significance of Dictionaries.
Ans: Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.
Qus. Why is a dictionary termed as an unordered collection of objects?
Ans: But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list. In dictionaries there is no index. It uses its keys as index which can be rearranged. That‘s why a dictionary termed as an unordered collection of objects
Qus. How is clear() function different from del <dict> Statement?
Ans: clear() removes all the elements of a dictionary and makes it empty dictionary while del statement removes the complete dictionary as an object. After del statement with a dictionary name, that dictionary object no longer exists, not even empty dictionary.
Programs
WAP to find the 2nd largest number from the list of the numbers entered through keyboard.
Write a python program that creates a list of numbers from 1 to 20 that are divisible by 4
Write a python program to define a list of countries that are a member of BRICS. Check whether a county is member of BRICS or not
Python program to read marks of six subjects and to print the marks scored in each subject and show the total marks
Python program to read prices of 5 items in a list and then display sum of all the prices, product of all the prices and find the average
Python program to count the number of employees earning more than 1 lakh per annum. The monthly salaries of n number of employees are given
Write a program to create a list of numbers in the range 1 to 10. Then delete all the even numbers from the list and print the final list.
Write a program to generate in the Fibonacci series and store it in a list. Then find the sum of all values.
Write a python program using a function that returns the area and circumference of a circle whose radius is passed as an argument.two values using tuple assignment
Write a program that has a list of positive and negative numbers. Create a new tuple that has only positive numbers from the list
Python Program that generate a set of prime numbers and another set of even numbers. Demonstrate the result of union, intersection, difference and symmetirc difference operations.
WAP that repeatedly asks the user to enter product names and prices. Store all of them in a dictionary whose keys are product names and values are prices. And also write a code to search an item from the dictionary.
WAP to create a dictionary named year whose keys are month names and values are their corresponding number of days.
write a program that input a list, replace it twice and then prints the sorted list in ascending and descending order.
write a program to check if the maximum element of the list lies in the first half of the list or in the second half.
write a program to input two lists and display the maximum elements from the elements of both the list combined, along with its index in its list.
write a program to input a list of numbers and swap elements at the even location with the elements at the odd location.
Write a program rotates the elements of a list so that the elements at the first index moves to the second index , the element in the second index moves to the third index, etc., and the element at the last index moves to the first index.
Write a program to input ‘n’ numbers and store it in a tuple and find maximum & minimum values in the tuple.
Ask the use to enter a list containing number between 1 and 12, then replace all the entries in the list that are greater than 10 with 10
Write a python program that inputs two lists and creates a third, that contains all elements of the first followed by all elements of the second.
Ask the user to inter list of string. Create a new list that consist of those strings with their first characters removed.
Write a Python program to Create a list using for loop which consist of integers 0 through 49
Write a Python program to create a list using for loop which consist square of the integers 1 through 50
Write a Python program to create a list using for loop which consist ['a','bb','ccc','dddd',....] that ends with 26 copies of the letter z.
Write a python program that takes any two list L and M of the same size and adds their elements together to from a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L=[3,1,4] and M= [1,5,9] the N should equal [4,6,13].
Write a python program to rotates the elements of a list so that the elements at the first index moves to the second index, the element in the second index moves to the third index, etc. and the elements in the last index moves to the first index.
Write a Python program display the maximum and minimum values form specified range of indexes of a list
Write a python program to compare two equal sized list and print the first index where they differ
Write a Python program to enter names of employees and their salaries as input and store them in a dictionary
Write a program to convert a number entered by the user into its corresponding number in words.
For example, if the input is 876 then the output should be 'Eight Seven Six'.
Repeatedly ask the user to enter a team name and how many games the team has won and how many they lost. Store this information in a dictionary where the keys are the team names and the values are a list of the form [wins, losses ].
(i) using the dictionary created above, allow the user to enter a team name and print out the team’s winning percentage.
(ii) using dictionary create a list whose entries are the number of wins for each team.
(iii) using the dictionary, create a list of all those teams that have winning records.
Write a program that repeatedly asks the user to enter product names and prices. Store all of these in a dictionary whose keys are the product names and whose values are the price .
When the user is done entering products and price, allow them to repeatedly enter a product name and print the corresponding price or a message if the product is not in dictionary.
Create a dictionary whose keys are month name and whose values are number of days in the corresponding month:
(a) ask the user to enter the month name and use the dictionary to tell how many days are in month .
(b) print out all of the keys in alphabetical order .
(c) print out all of the month with 31 days.
(d) print out the (key - value) pair sorted by the number of the days in each month .
Can you store the detail of 10 students in a dictionary at the same time? details include – rollno, name ,marks ,grade etc. Give example to support your answer.
Given the dictionary x = {‘k1’: ‘v1’, ‘k2’ : ‘v2’, ‘k3’ : ‘v3’} ,create a dictionary with the opposite mapping.
Write a program to create the dictionary .
Given two dictionaries say d1 and d2
Write a program that lists the over lapping keys of the two dictionaries if a key of d1 is also a key of d2 , the list it .
Write a program to check if a dictionary is contained in another dictionary.
e.g., if
d1 = {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15}
Then d1 is contained in d2.
A dictionary D1 has values in the form of lists of numbers. Write a program to create a new dictionary D2 having same keys as D1 but values as the sum of the list elements.
e.g.
D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}
Then
D2 is {'A':6, 'B': 15}
A dictionary has three keys: 'assets', 'liabilities' and 'capital'. Each of these keys store their value in form of a list storing various values of 'assets', liabilities' and 'capital' respectively. Write a program to create a dictionary in this form and print. Also test if the accounting equation holds true.