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. 1 : Which of the following is a Python tuple?

  1. [1, 2, 3]
  2. (1, 2, 3)
  3. {1, 2, 3}
  4. {}
Qus. 2 : Suppose t = (1, 2, 4, 3), which of the following is incorrect?

  1. print(t[3])
  2. t[3] = 45
  3. print(max(t))
  4. print(len(t))
Qus. 3 :

What will be the output of the following Python code?

  1. >>>t=(1,2,4,3)
  2. >>>t[1:3]


  1. (1, 2)
  2. (1, 2, 4)
  3. (2, 4)
  4. (2, 4, 3)
Qus. 4 :

What will be the output of the following Python code?

  1. >>>t=(1,2,4,3)
  2. >>>t[1:-1]


  1. (1, 2)
  2. (1, 2, 4)
  3. (2, 4)
  4. (2, 4, 3)
Qus. 5 :

What will be the output of the following Python code?

  1. >>>t = (1, 2, 4, 3, 8, 9)
  2. >>>[t[i] for i in range(0, len(t), 2)]


  1. [2, 3, 9]
  2. [1, 2, 4, 3, 8, 9]
  3. [1, 4, 8]
  4. (1, 4, 8)
Qus. 6 :

What will be the output of the following Python code?

  1.   d = {"john":40, "peter":45}
  2.   d["john"]


  1. 40
  2. 45
  3. “john”
  4. “peter”
Qus. 7 :

What will be the output of the following Python code?

  1. >>>t = (1, 2)
  2. >>>2 * t


  1. (1, 2, 1, 2)
  2. [1, 2, 1, 2]
  3. (1, 1, 2, 2)
  4. [1, 1, 2, 2]
Qus. 8 :

What will be the output of the following Python code?

  1. >>>t1 = (1, 2, 4, 3)
  2. >>>t2 = (1, 2, 3, 4)
  3. >>>t1 < t2


  1. True
  2. False
  3. Error
  4. None
Qus. 9 :

What will be the output of the following Python code?

  1. >>>my_tuple = (1, 2, 3, 4)
  2. >>>my_tuple.append( (5, 6, 7) )
  3. >>>print len(my_tuple)


  1. 1
  2. 2
  3. 5
  4. Error
Qus. 10 :

What will be the output of the following Python code?

  1.   numberGames = {}
  2.   numberGames[(1,2,4)] = 8
  3.   numberGames[(4,2,1)] = 10
  4.   numberGames[(1,2)] = 12
  5.   sum = 0
  6. for k in numberGames:
  7.       sum += numberGames[k]
  8.   print len(numberGames) + sum


  1. 30
  2. 24
  3. 33
  4. 12
Qus. 11 : What is the data type of (1)?

  1. Tuple
  2. Integer
  3. List
  4. Both tuple and integer
Qus. 12 : If a=(1,2,3,4), a[1:-1] is _________

  1. Error, tuple slicing doesn’t exist
  2. [2,3]
  3. (2,3,4)
  4. (2,3)
Qus. 13 :

What will be the output of the following Python code?

>>> a=(1,2,(4,5))  >>> b=(1,2,(3,4))  >>> a<b


  1. False
  2. True
  3. Error, &lt; operator is not valid for tuples
  4. Error, &lt; operator is valid for tuples but not if there are sub-tuples
Qus. 14 :

What will be the output of the following Python code?

>>> a=("Check")*3  >>> a


  1. (‘Check’,’Check’,’Check’)
  2. * Operator not valid for tuples
  3. (‘CheckCheckCheck’)
  4. Syntax error
Qus. 15 :

What will be the output of the following Python code?

>>> a=(2,3,4)  >>> sum(a,3)


  1. Too many arguments for sum() method
  2. The method sum() doesn’t exist for tuples
  3. 12
  4. 9
Qus. 16 :

Is the following Python code valid?

>>> a=(1,2,3,4)  >>> del a


  1. No because tuple is immutable
  2. Yes, first element in the tuple is deleted
  3. Yes, the entire tuple is deleted
  4. No, invalid syntax for del method
Qus. 17 : What type of data is: a=[(1,1),(2,4),(3,9)]?

  1. Array of tuples
  2. List of tuples
  3. Tuples of lists
  4. Invalid type
Qus. 18 :

What will be the output of the following Python code?

>>> a=(0,1,2,3,4)  >>> b=slice(0,2)  >>> a[b]


  1. Invalid syntax for slicing
  2. [0,2]
  3. (0,1)
  4. (0,2)
Qus. 19 :

Is the following Python code valid?

>>> a,b,c=1,2,3  >>> a,b,c


  1. Yes, [1,2,3] is printed
  2. No, invalid syntax
  3. Yes, (1,2,3) is printed
  4. 1 is printed
Qus. 20 :

Is the following Python code valid?

>>> a,b=1,2,3


  1. Yes, this is an example of tuple unpacking. a=1 and b=2
  2. Yes, this is an example of tuple unpacking. a=(1,2) and b=3
  3. No, too many values to unpack
  4. Yes, this is an example of tuple unpacking. a=1 and b=(2,3)
Qus. 21 :

What will be the output of the following Python code?

>>> a=(1,2)  >>> b=(3,4)  >>> c=a+b  >>> c


  1. (4,6)
  2. (1,2,3,4)
  3. Error as tuples are immutable
  4. None
Qus. 22 :

What will be the output of the following Python code?

>>> a,b=6,7  >>> a,b=b,a  >>> a,b


  1. (6,7)
  2. Invalid syntax
  3. (7,6)
  4. Nothing is printed
Qus. 23 :

What will be the output of the following Python code?

>>> import collections  >>> a=collections.namedtuple('a',['i','j'])  >>> obj=a(i=4,j=7)  >>> obj


  1. a(i=4, j=7)
  2. obj(i=4, j=7)
  3. (4,7)
  4. An exception is thrown
Qus. 24 :

Is the following Python code valid?

>>> a=2,3,4,5  >>> a


  1. Yes, 2 is printed
  2. Yes, [2,3,4,5] is printed
  3. No, too many values to unpack
  4. Yes, (2,3,4,5) is printed
Qus. 25 :

What will be the output of the following Python code?

>>> a=(2,3,1,5)

>>> a.sort() 

>>> a



  1. (1,2,3,5)
  2. (2,3,1,5)
  3. None
  4. Error, tuple has no attribute sort
Qus. 26 :

Is the following Python code valid?

>>> a=(1,2,3)  >>> b=a.update(4,)


  1. Yes, a=(1,2,3,4) and b=(1,2,3,4)
  2. Yes, a=(1,2,3) and b=(1,2,3,4)
  3. No because tuples are immutable
  4. No because wrong syntax for update() method
Qus. 27 :

What will be the output of the following Python code?

>>> a=[(2,4),(1,2),(3,9)]  >>> a.sort()  >>> a


  1. [(1, 2), (2, 4), (3, 9)]
  2. [(2,4),(1,2),(3,9)]
  3. Error because tuples are immutable
  4. Error, tuple has no sort attribute
Qus. 28 :

What will be the output of the following Python code?

nums = set([1,1,2,3,3,3,4,4])

print(len(nums))



  1. 7
  2. Error, invalid syntax for formation of set
  3. 4
  4. 8
Qus. 29 :

What will be the output of the following Python code?

a = [5,5,6,7,7,7]

  b = set(a)  def test(lst):      if lst in b:          return 1      else:          return 0  for i in  filter(test, a)

print(i,end=" ")



  1. 5 5 6
  2. 5 6 7
  3. 5 5 6 7 7 7
  4. 5 6 7 7 7
Qus. 30 : <p>What is the output of the following code ?</p><pre>ms = ('A','D', 'H','U','N','I','C')<br>print(ms[1:4])</pre>

  1. (‘D’, ‘H’, ‘U’)
  2. (‘A’, ‘D’, ‘H’,’U’,’N’,’I’,’C’)
  3. (‘D’,’H’,’U’,’N’,’I’,’C’)
  4. (‘D’,’H’,’U’,’N’,’I’,’C’)
Qus. 31 : <p>What is the output of the following statement ?</p><pre>print ((2, 4) + (1, 5))</pre>

  1. (2 , 4), (4 , 5)
  2. (3 , 9)
  3. (2, 4, 1, 5)
  4. Invalid Syntax
Qus. 32 : <p>What is the output of the following?</p><pre style="font-size: 12.6px; letter-spacing: 0.14px;">print(max([1, 2, 3, 4.] [4, 5, 6], [7]))</pre>

  1. [4,5, 6
  2. [7]
  3. [1, 2,3, 4]
  4. 7
Qus. 33 : Which one of the following is inmmutable data type?

  1. list
  2. set
  3. tuple
  4. dict
Qus. 34 : <p>What will be the output of the following Python code?</p><pre>tuple1=(5,1,7,6,2)<br>tuple1.pop(2)<br>print(tuple1)</pre><div><br></div>

  1. (5,1,6,2)
  2. (5,1,7,6)
  3. (5,1,7,6,2)
  4. Error
Qus. 35 : Choose the correct option with respect to Python..

  1. In Python, a tuple can contain only integers as its elements.
  2. In Python, a tuple can contain only strings as its elements.
  3. In Python, a tuple can contain both integers and strings as its elements.
  4. In Python, a tuple can contain either string or integer but not both at a time.
Qus. 36 : <p>What will be the output of the following code?</p><pre><span style="font-size: 14px;">a=((0,2,3,4)[1:-2])<br></span><span style="font-size: 14px;">print(a)</span></pre><div><br></div>

  1. (3,)
  2. (2, )
  3. (1,)
  4. (0,)
Qus. 37 : List is mutable and Tuple is immutable?

  1. Yes, list mutable and tuple immutable
  2. No, list and tuple both are mutable
  3. No, list and tuple both are in immutable
  4. No, just opposite, list immutable and tuple mutable
Qus. 38 : What type of data is : arr=[(1,1),(2,2),(3,3)]?

  1. List of tuple
  2. Tuple of List
  3. Array of Tuples
  4. Invalid Type

Programs

python program to find the 2nd largest number from the list of the numbers entered through keyboard.

View Solution


python program that creates a list of numbers from 1 to 20 that are divisible by 4

View Solution


python program to define a list of countries that are a member of BRICS Check whether a county is member of BRICS or not

View Solution


Python program to read marks of six subjects and to print the marks scored in each subject and show the total marks

View Solution


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

View Solution


Python program to count the number of employees earning more than 1 lakh per annum

View Solution


python 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

View Solution


python program to generate in the Fibonacci series and store it in a list Then find the sum of all values

View Solution


python program to swap two values using tuple assignment

View Solution


python program using a function that returns the area and circumference of a circle whose radius is passed as an argument

View Solution


python program that has a list of positive and negative numbers Create a new tuple that has only positive numbers from the list

View Solution


Python Program that generate a set of prime numbers and another set of even numbers

View Solution


python program to find minimum element from a list of elements along with its index in the list

View Solution


Python program to calculate mean of a given list of numbers

View Solution


Python program to search for an element in a given list of numbers

View Solution


python program to count frequency of a given element in a list of numbers

View Solution


python program to calculate the sum of integers of the list

View Solution


python program to reverses an array of integers

View Solution


python program to creates a third list after adding two lists

View Solution


python program to store the product information in dictionary

View Solution


python program to create a dictionary whose keys are month names and values are their corresponding number of days

View Solution


python program that input a list, replace it twice and then prints the sorted list in ascending and descending order

View Solution


python program to check if the maximum element of the list lies in the first half of the list or in the second half

View Solution


python program to display the maximum elements from the two list along with its index in its list

View Solution


python program to swap list elements with even and locations

View Solution


python program to rotate list elements with next elements

View Solution


python program to find maximum and minimum values in tuple

View Solution


python program to interchange the values of two tuple

View Solution


python program to interchange the values of two tuple

View Solution


python program to increment the elements of list

View Solution


python program 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

View Solution


python program that reverse the list of integers in place

View Solution


python program to input two list and create third list which contains all elements of the first elements followed by all elements of second list

View Solution


python program to inter list of string and create a new list that consist of those strings with their first characters removed

View Solution


python program to create a list using for loop which consist of integers 0 through 49

View Solution


python program to create a list using for loop which consist square of the integers 1 through 50

View Solution


python program to create a list using for loop which consist a bb ccc dddd that ends with 26 copies of the letter z.

View Solution


python program that takes any two list L and M of the same size and adds their elements together in another third list

View Solution


python program to rotates the elements of list so that fist elements move to second and second to the third

View Solution


python program to move all duplicate element to the end of list

View Solution


python program to display the maximum and minimum values form specified range of indexes of a list

View Solution


python program to compare two equal sized list and print the first index where they differ

View Solution


python program to enter names of employees and their salaries as input and store them in a dictionary

View Solution


python program to count the number of times a character appears in a given string

View Solution


python program to convert a number entered by the user into its corresponding number in words

View Solution


python program Repeatedly ask the user to enter a team name

View Solution


python program that repeatedly asks the user to enter product names and prices

View Solution


Python Program to Create a dictionary whose keys are month name and whose values are number of days in the corresponding month

View Solution


python program to store the detail of 10 students in a dictionary at the same time

View Solution


python program to Create a dictionary with the opposite mapping

View Solution


python 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

View Solution


python program that checks if two same values in a dictionary have different keys

View Solution


python program to check if a dictionary is contained in another dictionary

View Solution


python program to create a new dictionary D2 having same keys as D1 but values as the sum of the list elements

View Solution


python program to create a dictionary has three keys assets liabilities and capital

View Solution


python program that create a tuple storing first 9 terms of Fibonacci series

View Solution


python program that receives the index and return the corresponding value

View Solution


Python program that receives a Fibonacci series term and returns a number telling which term it is

View Solution


python program to create a nested tuple to store roll number name and marks of students

View Solution


python program that interactively creates a nested tuple to store the marks in three subjects for five students

View Solution


Python Program to accept three distinct digits and print all possible combinations from the digits

View Solution


Python Program to find the successor and predecessor of the largest element in list

View Solution


Python function that takes a string as parameter and returns a string with every successive repetitive character replaced

View Solution


CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online Exam Quiz O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Best Website and Software Company in Allahabad Website development Company in Allahabad