Tuple Datatype

The Tuple data type is the same as List Datatype except that it is Immutable, that means once you create any tuple, you cannot make any changes to that.

The tuple is a Read-only version of List, which means we cannot add, remove and replace any elements.

The syntax for the Tuple is

Tuple=(Elements)

Example:

 Tuple=(10,20,30, "banana")
print(type(Tuple))
##The output is:
<class 'tuple'>

The properties of Tuple are:

  • Order is preserved
  • Duplicate values are allowed
  • Should be mentioned in parentheses()
  • Heterogeneous objects are allowed
  • Indexing concept is applicable
  • Slicing concept is applicable in Tuple data type
  • We cannot Add and Remove the elements from the List
  • And Tuple is Immutable

Example:

Tuple=(10,20,30,"banana")
print(tuple[0])
print(tuple[-1])
print(Tuple[1:4])
##The output is:
10
banana
(20, 30, 'banana')

But we cannot perform any changes in the content

Tuple=(10,20,30,"banana")
Tuple[0]=5
ptint(Tuple)
##The output is:
 Tuple[0]=5
TypeError: 'tuple' object does not support item assignment ## Type Error

While representing the single-valued tuple, we have to represent the tuple element followed by a comma or else python will consider the single value tuple as an int value.

Example: Representing a single-valued tuple will be considered as an int object

Tuple=(5)
print(type(Tuple))

single-value-tuple-considered-as-int

Example: While representing the single-valued tuple, we have to represent the tuple object followed by a comma.

Tuple=(12,)
print(type(Tuple))

representing-the-single-valued-tuple-with-comma

Parenthesis is optional for the tuple datatype we may or may not represent the tuple object in the parenthesis.

Tuple=12,13,
print(type(Tuple))

representing-the-tuple-object-without-parenthesis

The empty tuple is a valued Tuple

Tuple=()
print(type(Tuple))

empty-tuple

Some of the valid and invalid ways of representing the tuple objects are:

Tuple=()
ptint(type(Tuple))
Tuple=(19)##Invalid
ptint(type(Tuple))
Tuple=18 ##Invalid
ptint(type(Tuple))
Tuple=(13,)
ptint(type(Tuple))
Tuple=13,
ptint(type(Tuple))
Tuple=(11,12,13)
ptint(type(Tuple))
Tuple=10,20,30
ptint(type(Tuple))
Tuple=(10,20,30,)
ptint(type(Tuple))
Tuple=10,20,30,
ptint(type(Tuple))

different-type-of-representation-of-tuple

Python Input and Output Statements

Different ways of Creating Tuple Object

Some of the valid and invalid ways of representing the tuple objects are:

##Empty tuple
Tuple=()
print(type(Tuple))

##Invalid Tuple
Tuple=(19)
print(type(Tuple))

##Invalid Tuple
Tuple=18

##Single valued tuple
print(type(Tuple))
Tuple=(13,)
print(type(Tuple))
Tuple=13,

##Multi valued tuple
print(type(Tuple))
Tuple=(11,12,13)
print(type(Tuple))
Tuple=10,20,30
print(type(Tuple))
Tuple=(10,20,30,)
print(type(Tuple))
Tuple=10,20,30,
print(type(Tuple))

different-type-of-representation-of-tuple

Creating a tuple by using the tuple() function:

We can create a tuple by using the tuple()function, the syntax for the tuple() function is

T=tuple(sequence)

By using the tuple() function we can pass any kind of sequence, that sequence will be converted into a tuple.

Example:

List=[22,33,44]
New_tuple=tuple(List)
print(New_tuple)

converting-list-into-tuple

Example: We can also create a tuple by using a range.

##New_tuple=tuple(range(begin,end,step value/increment value)
New_tuple=tuple(range(45,56,96))
print(New_tuple)

creating-tuple-by-using-range

Example: When we pass any string then each character will act as an element in the tuple

Data=tuple("Mountain")
print(Data)

converting-string-into-tuplestring

Example: Creating a tuple with dynamic input by using the eval() function

Tuple=eval(input("Enter the tuple values"))
print(type(Tuple))

creating-tuple-by-using-eval-function

Python Command Line Arguments

Accessing Tuple Objects by using Indexing and Slicing Operator

By using the index operator:

  • The Tuple supports for the zero-based index, the index of the first element is zero.
  • The Tuple supports both positive indexing and negative indexing.
  • The positive indexing means forward direction(-->) or from left to right.
  • The negative indexing means, backward direction(<--) or from right to left.

We can access the elements of the tuple by using the index operator

Tuple=(10,20,30,40,50,60,70,80,90)
print(tuple[0])
print(tuple[1])
print(tuple[100])
##The output is:
Traceback (most recent call last):
  File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 4, in <module>
    print(Tuple[100])
IndexError: tuple index out of range
10
20

When we try to access the index of the element which is not present in the tuple, then python will throw an index error.

accessing-tuple-elements-by-using-index-operator-

By using the slice operator:

We can access the tuple elements by using the slice operator.

The syntax for the slice operator is:

Tuple[begin:end:step]

Begin: The integer where the beginning of a slicing object will start.
End: The integer until which the slicing will take place or slicing will stop.
Step: Integer which determines the increment between each index for slicing.

  • The step value can be either +ve or -ve
  • If the step value is +ve then, we have to consider from the begin to end-1 in Forward direction(From left to right)
  • If the step value is -ve then, we have to consider from the begin to end+1 in Backward direction(From right to left)
  • In the backward direction if the step value -1 then the result is always empty.
  • In the forward direction if the step value 0 then the result is always empty.
  • In Forward Direction:
    The default value for begin is 0
    The default value for the end is the length of the string
    The default value for step is +1
  • In Backward Direction:
    The default value for begin is -1
    The default value for the end is -(length of the string+1)
  • We can consider both +ve and -ve values for beginning and end index in case of forwarding and backward directions.

Example:

tuple=(10,20,30,40,50,60,70,80,90)
print(tuple[2:5])
print(tuple[: : 2])

accessing-tuple-elements-by-using-slice-operator

Python Flow Control

Concatenation and Repetition Operator for Tuple

Concatenation operator for Tuple:

We can add the elements of the two Tuples by using the concatenation operator(+).

Tuple1=(10,20,30)
Tuple2=(40,50,60)
Tuple3=Tuple1+Tuple2
print(Tuple3)

concatenating-tuples

To perform concatenation both the arguments should be of tuple datatype only if we try to add tuple with any integer then python will throw an error

Tuple1=(1,2,3)
Tuple2=10
tuple3=Tuple1+Tuple2
print(Tuple3)
##The output is:
Traceback (most recent call last):
  File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 3, in <module>
    tuple3=Tuple1+Tuple2
TypeError: can only concatenate tuple (not "int") to tuple

Repetition Operator for Tuple:

To repeat, the elements present inside the tuple for the specified number of times we use repetition operator.

To use the repetition operator one argument must be of Tuple data type and another must be of int type.

Tuple=(45,55,65)
New_Tuple=Tuple1*3
print(New_Tuple)

repeating-tuple-elements

Example:

Tuple1=(10,20)
Tuple2=(30,40)
Tuple3=Tuple2+Tuple3
Tuple4=Tuple3*3

concatenation-and-repetation-tuple

Python String and Declaring String

Equality Operator for Tuple

We can use the equality operator to compare the elements of two objects. The operators which are used to compare the Tuple elements are

  • Equal to(==)
  • Not equal(!=)

Python Returns True when

  • The number of Elements of the two Tuple must be the same.
  • The Order of elements must be the same.
  • The content of elements including the case must be the same.
Tuple1=('Cat','Rat','Dog')
Tuple2=('Cat','Rat','Dog')
Tuple3=('CAT','RAT','DOG')
Tuple4=('Rat','cat','dog')
print(Tuple1==Tuple2)
print(Tuple2==Tuple3)
print(Tuple2!=Tuple3)
print(Tuple3==Tuple4)
print(Tuple4==Tuple1)

comparing-tuple-elements

Python Introduction

Relational Operator for Tuple

The relational operator compares the first element of the Tuple and returns True or False depending on the conditions given.

The Relational Operators are:

  • Less Than
  • Greater Than
  • Less Than or Equal to
  • Greater Than or Equal to

Example:

Tuple1=(34,24,44)
Tuple2=(12,24,36)
print(Tuple2<Tuple1)

comparing-tuple-objects

If the first elements of both the tuples are equal, then it will check for the second element and returns whether it is true or false

omparing-seond-element-of-tuple

Python Installation

Membership Operator for Tuple

Python supports to check whether the given character or a string is a member of any Tuple or not by using the in and not in operators.

The following example demonstrates the membership operator

Tuple=(10,26,44)
print(10 in Tuple)
print(50 in Tuple)
print(65 not in Tuple)

The output is:

mebership-operator-for-tuple

Methods and Functions of Tuple

Python provides Functions and methods for Tuple Datatype

Tuple functions:

Thelen() function provides the total length/Number of elements present in the Tuple.

The syntax for the Tuple is

len(Tuple)

The following example demonstrates the len() function

Tuple=(12,24,36,48)
print(len(Tuple))

The output is:

len-funtions-for-tuple

Tuple Methods:

The count() method returns the number of occurrences of the specified element present in the tuple.

The syntax for the count() method is

Tuple=(1,2,3,4,1,2,5,6,7)
print(count(Tuple))

The output is:

count-function-for-tuple

The index() method returns the first occurrence of the specified element present in the Tuple

The syntax for the index() method

Tuple=(10,20,30,10,40,50)
print(Tuple.index(10))

The output is:

index-function-for-tuple

If the specified element is not present in the given tuple, then the index method will throw a value error

index-value-error-in-tuple

Installing pydev with Eclipse

Reversing and Sorting of Tuple elements

Reversing Tuple elements:

The python does not support the reversing of the tuple elements because the tuple is immutable,

but we can perform the reversed operation by creating a new tuple from the reversed objects.

The syntax for the reversed() function is:

Rversed(Tuple)

The following example demonstrates the reversed() function

Tuple1=(10,20,30,40)
R=reversed(Tuple1)
Tuple2=tuple(R)
print("Original Tuple:",Tuple1)
print("Revrsed Tuple:",Tuple2)

The output is:

reversing-tuple-elements

Sorting Tuple Elements:

Python does not support sorting of elements present in the tuple, because the tuple is immutable, but we can sort the elements of the tuple by using the sorted() function.

But the sorted() function will return the list as the output, we can convert the sorted list into a new tuple by using the tuple() function.

The following example demonstrates the sorting of tuple elements

Tuple1=(35,21,60,20)
List=sorted(Tuple1)
Tuple2=tuple(List)
print("Original Tuple:",Tuple1)
print("Revrsed Tuple:",Tuple2)

The output is:

sorting-of-tuple-elements

The sorted() function is going to sort the elements in the ascending order if we want to print the tuple elements in the descending order then, we have to follow the below method

Tuple1=(35,21,60,20)
List=sorted(Tuple1,reverse=True)
Tuple2=tuple(List)
print("Original Tuple:",Tuple1)
print("Revrsed Tuple:",Tuple2)

The output is:

sorting-tuple-elements-in-descending-order

Variables and Data types in Python

Max and Mini Functions for Tuple

The max() and min() functions are the pythons built-in functions where max() function returns the maximum value among the given tuple elements.

And min() function returns the minimum value among the given Tuple elements.

We can apply these functions in any kind of python datatypes because these functions are python built-in functions.

The following example demonstrates the use of max() and min() functions:

max-and-min-value

Packing and Unpacking of Tuple

The packing and Unpacking are the two built-in functions of python, wherein packing we assign the values into a new tuple and in case of unpacking, we extract those values into a single variable.

The following example demonstrates the packing of tuple elements:

a=10
b=20
c=30
d=40
Tuple=a,b,c,d
print(Tuple)

The output is:

packing-of-tuple-elements

The Following example demonstrates unpacking of tuple elements

Tuple=(11,12,13,14)
a,b,c,d=Tuple
print(Tuple)

The output is:

unpacking-of-tuple-elements

Incase of unpacking the number of values and number of variables must be the same otherwise python will throw a value error.

Tuple=(11,12,13,14)
a,b,c=Tuple
print(Tuple)
##The output is:
Traceback (most recent call last):
  File "C:UsersAnup kumareclipse-workspaceFirstProjectPythonFirstPythonPackageFirstPythonModule.py", line 2, in <module>
    a,b,c=Tuple
ValueError: too many values to unpack (expected 3)

Python Datatype summary

Tuple Comprehension

The comprehension concept is not applicable for the Tuple data type, it is applicable for the list datatype.

If you try to apply for the tuple then python returns the generator object.

The following example demonstrates the Comprehension in the tuple

comprehension-in-tuple

Difference between List and Tuple

List and Tuple are exactly the same except small difference: List objects are mutable whereas Tuple objects are immutable.

In both cases insertion, the order is preserved, duplicate objects are allowed, heterogeneous objects are allowed, index and slicing are supported.

List Tuple
The list is a Group of Comma-separated Values within Square Brackets and Square Brackets are mandatory. Eg: i = [10, 20, 30, 40] The tuple is a Group of Comma-separated Values within Parenthesis and Parenthesis are optional. Eg: t = (10, 20, 30, 40) t = 10, 20, 30, 40
List Objects are Mutable i.e. once we create List Object we can perform any changes in that Object. Eg: i[1] = 70 Tuple Objects are Immutable i.e. once we create Tuple Object we cannot change its content. t[1] = 70 ValueError: tuple object does not support item assignment
If the Content is not fixed and keeps on changing then we should go for List. If the content is fixed and never changes then we should go for Tuple.
List Objects can not be used as Keys for Dictionaries because Keys should be Hashable and Immutable. Tuple Objects can be used as Keys for Dictionaries because Keys should be Hashable and Immutable.

A program to read the Tuple of numbers from the keyboard and print its Sum and Average

Tuple=eval(input("Enter Tuple of numbers:"))
print("The sum:",sum(Tuple))
print("The Average:",sum(Tuple)/len(Tuple))

The output is:

printing-avaerage-and-sum-of-tuple-elements






Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions