Python Tuple with Examples | Tuple in Python 3

Preview
You must first complete Python List with Examples | List in Python 3 before viewing this Lesson

What is a Tuple in Python 3?

Tuple  is a collection of values within pair of parenthesis. These values must be separated by commas. These values can be of any data type.

Tuples are immutable i.e. we can’t modify the elements of a tuple.

1. Creating a Tuple

To create a tuple, we can put multiple values within the pair of parenthesis.

Syntax:

tuplename= (value1,value2,value3,……. valueN )

tuplename refers to name of tuple defined by the programmer.

( ) Pair of parenthesis specifies that it is a tuple.

value1, value2,value3, …. valueN are different values stored in the tuple.

Examples:

( 1,2,3)Tuple of integers
( 1,2.5,3,9.5 )Tuple of numbers(integers and floating point)
(‘a’,’b’,’c’ )Tuple of characters
( ‘a’,1,’b’,3.5 )Tuple of mixed values
(‘First’,’Second’ )   Tuple of strings



2. Creating an empty tuple

Empty tuple contains no element in it.   It is equivalent of 0 or ‘ ‘(blank).  So it has truth value as False.

We can create an empty tuple in two ways:

a. By specifying an empty pair of square parenthesis

Tuple1=( )

Note:  Tuple1 is an empty tuple containing no element in it.

b. By using tuple() function without anything within the pair of parenthesis.

Tuple2=  tuple ( )

Note:  Tuple2 is an empty tuple containing no element in it.


3. Single Element Tuple

If  we give a single value within a pair of parenthesis, Python considers it a single variable value

Example 1

>>>t=(1)

>>>print(t)
1

To create a tuple with one element, we need to add a comma after single value within the pair of parenthesis:

Example 2

>>>t=3,

>>>print(t)    
(3,)

Example 3

>>>t=(3,)

>>>print(t)    
(3,)



4. Creating a Long Tuple

If tuple contains many  elements which are not  able to fit on one line, we can split it across several lines as given below:

tuple1=(10,20,30,40,50,60,70,80,90,100,

               120,130,140,150)

Opening parenthesis appears in the beginning and closing parenthesis appears at the end of tuple.

>>> tuple1=(10,20,30,40,50,60,70,80,90,100,

               120,130,140,150)

>>> tuple1
(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 130, 140, 150)

5. Nested tuple

If one tuple is enclosed within another tuple, it is known as nested tuple.

A tuple can contain another tuple as its  element. Such a tuple is called nested tuple

Example:

Tuple1=(1,2,(5,6,7),9)

Tuple1 is a nested tuple with four elements:3,4,(5,6,7)and9 .

Here (5,6,7) is nested tuple.

>>> tuple2=(1,2,(5,6,7),9)
>>> tuple2
(1, 2, (5, 6, 7), 9)



6. Creating  a Tuple from Existing Sequence

We can use tuple() function to create tuple from existing sequences as given below:

tuplename=tuple(<sequence>)

Here, tuplename refers to name of tuple specified by the programmer.

<sequence> refers to existing sequence object like string, tuple, set or other tuple

Python Creates the individual elements of the tuple from the individual elements of sequence.

Example 1:

Creating a tuple from existing string
>>> newtuple1=tuple(‘Lovejot’)
>>> newtuple1
(‘L’, ‘o’, ‘v’, ‘e’, ‘j’, ‘o’, ‘t’)
Description

Tuple named newtuple1 is created from string ‘lovejot’

It converts each individual character of string into individual tuple elements:

(‘L’, ‘o’, ‘v’, ‘e’, ‘j’, ‘o’, ‘t’)

Example 2: 

Creating a tuple from existing list
>>> list1=[1,3,5,7,9]
>>> newtuple2=tuple(list1)
>>> newtuple2
(1, 3, 5, 7, 9)
Description

Tuple named newtuple2 is created from existing list list1 = [1,3,5,7,9]

It converts each individual element of list  into individual tuple elements:

(1,3,5,7,9)

Example 3: 

Creating a tuple from existing set
>>> s1={2,4,6,8,10}
>>> newtuple3=tuple(s1)
>>> newtuple3
(2,4, 6,8,10)
Description

Tuple named newtuple3 is created from existing set s1 = {2,4,6,8,10}

It converts each individual element of set into individual tuple elements:

(2,4,6,8,10)

7. Reading a Tuple from keyboard

We can also use tuple() function to read elements of a tuple by using keyboard.

Example 1:

Reading tuple from keyboard
>>> tuple3=tuple(input(‘Enter tuple =’))
Enter tuple = India
>>> tuple3
(‘I’, ‘n’, ‘d’, ‘i’, ‘a’)
Description
String India is entered from keyboard and it gets converted into tuple as (‘I’, ‘n’, ‘d’, ‘i’, ‘a’)

Example 2:

Reading tuple from keyboard
>>> tuple3=eval(input(‘Enter tuple =’))
Enter tuple = (1,3,4,5)
>>> tuple3
(1,3,4,5)
Description
Tuple name tuple3 is entered from keyboard as (1,3,4,5)



8. Accessing elements of a Tuple

Each element of a tuple has an index associated with it.

Elements of a Tuple are also indexed in two ways:

  1. FORWARD INDEXING AS 0,1,2,3,…
  2. BACKWARD INDEXING AS -1,-2,-3,…

Example

we have a tuple named tuple1=(10,30,40,50,60,99)

Elements of above tuple are indexed as follows:

 

Index of first element of Tuple is 0 (Forward Indexing) and -6 (Backward Indexing)

So we an access first element of above tuple as tuple1[0] or tuple1[-6]

Similary we can access last element of above tuple as tuple1[5] or tuple1[-1].

Example

>>> classes=(‘xii’,’xi’,’x’,’ix’)
>>> classes[0]
‘xii’#First element of tuple is shown
>>> classes[2]
‘x’#Third  element of tuple is shown
>>> classes[-1]
‘ix’#Last element of tuple is shown
>>> classes[-3]
‘xi’#Second element of tuple is shown



9. Slicing of Tuple elements

We can view specific values in a tuple by specifying the range of indexes within the pair of parenthesis as: Tuplename(First_index,Last_index,Gap).
Tuplename is the name of tuple whose values you want to view.
First_index refers to the starting index.
Last_index refers to ending index.
Gap refers to the gap in indexes

Example

>>> tuple1=[10,20,30,40,50,60,70)
>>> tuple1[0:3]
(10, 20, 30)#Tuple elements at indexes 0,1,2 are shown.
>>> tuple1[2:6]
(30, 40, 50, 60)#Tuple elements at indexes 2,3,4,5 are shown.
>>> tuple1[-6:-3]
(20, 30, 40)#Tuple elements at indexes -6,-5,-4 are shown.
>>> tuple1[0:7:2]
(10, 30, 50, 70)
#Tuple elements at indexes 0,2,4,6 are shown.
>>> tuple1[-7:-2:2]
(10, 30, 50)
#Tuple elements at indexes -7,-5,-3 are shown.
>>> tuple1[::2]
(10, 30, 50)
#All tuple elements starting from index 0 onwards will be shown with a gap of 2 i.e.elements at  indexes 0,2,4 are shown.

10. Find number of elements in tuple

Function len() of Python returns number of elements in a tuple. The syntax of len() is

len(tuplename)

tuplename refers to existing tuple whose length we want to fine.

Example

Python Code
>>> classes=(‘xii’,’xi’,’x’,’ix’)
>>> len(classes)
4

Description

Length of tuple classes is returned as 4 because there are four values in the tuple.



11. Membership operators on Tuple

We can use ‘in’ and ‘not in’ operators with Tuples

Example:

>>> tuple1=(10,20,30,40,50,60,70)
>>> 10 in tuple1
True#Output is True because 10 is contained in the tuple.
>>> 25 in tuple1
False#Output is False because 25 is not contained in the tuple.
>>> 25 not in tuple1
True#Output is True because 25 is not contained in the tuple.
>>> 20 not in tuple1
False#Output is False because 20 is contained in the tuple.



12. Concatenation Operator on Tuple

We can concatenate two tuples together by using concatenation operator (+).

Example:

>>> tuple1=(11,22,33)
>>> tuple2=(40,50,60)
>>> tuple1+tuple2
(11, 22, 33, 40, 50, 60)#Elements of tuple1 and tuple2 are joined together.
>>> tuple1[0:2]+tuple2[1:3]
(11, 22, 50, 60)#Elements of tuple1 at indexes 0,1 and elements of tuple2 at indexes 1,2 are joined together.

It should be noted that only one tuples can be concatenated with another tuple. Tuple can’t be concatenated with non tuple value.

Example:

(1,3)+4 will give error as tuple (1,3) is added to integer value 4.

13. Replication Operator on Tuple

We can use replication operator (*)to repeat a tuple.

Example:

>>> tuple1=(11,22,33,44)
>>> tuple1*2
(11, 22, 33, 44,11, 22, 33,44)#Elements of tuple1 are repeated twice in the output.
>>> tuple1[0:2]*2
(11, 22,11, 22)#Elements of tuple1 at indexes 0 and 1are repeated twice.



14. Comparison of Tuples

We can compare two tuples using relational operators of Python

If all elements are two tuples are same, then two tuples are considered equal.  Tuples to be compared must be of same type.

Elements  of tuple are compared one by one. If any comparison is wrong, False is returned.

Example:

>>> tuple1=(11,22,33)
>>> tuple2=(11,22,33)
>>> tuple3=(12,23,34)
>>> tuple4=(12,25)
>>> tuple5=(12,23,33)
>>> tuple1==tuple2
True #Elements of tuple1 and tuple2 are same, So True is returned
>>> tuple1<tuple2
False#Elements of tuple1 and tuple2 are same, So False is returned
>>> tuple1<tuple3
True#All elements of tuple1 are less than tuple2, So True is returned.
>>> tuple1>tuple3
False#All elements of tuple1 are less than tuple2, So False is returned.
>>> tuple1<tuple4
True#Only first two elements of tuple1 are compared to tuple4. As first two elements of tuple1 are less than first two elements of tuple4, True is returned.
>>> tuple3<tuple5
False
#First two elements of tuple3 and tuple5 are same but third element of tuple3 is not less than tuple5. So False is returned.




15. Unpacking Tuples

To Create a tuple from a set  of values is called packing and creating individual values from a tuple’s elements is called unpacking.

Syntax for unpacking in Python:

<variable1>,<variable2>,<variable3>,…=tuplename

Number of variables at left side of assignment must match the number of elements in the tuple at right side.

Example

We Have A Tuple as t1=(1,3,5,6)

There are four elements in it .

To unpack it, we can write:

a,b,c,d=t1

First element of tuple will be assigned to variable a.

Second element of tuple will be assigned to variable b.

Third element of tuple will be assigned to variable c.

Fourth element of tuple will be assigned to variable d.

Example:

>>> t1=[1,3,5,6]

>>> a,b,c,d=t1

>>> print(a,b,c,d)
1 3 5 6

Description
 Value of a is printed as 1, b as 3, c as 5 and d as 6.



16. Deleting Tuples

We can use del statement to delete an entire tuple. We can’t delete individual elements of a tuple as they are immutable

For example, We have a tuple named t1=(1,3,5,9)

It can be deleted as

del t1

Example:

Python Code

>>> t1=[1,3,5,6]

>>del t1

>>> t1

Traceback (most recent call last):

  File “<pyshell#11>”, line 1, in <module>

    t1

NameError: name ‘t1’ is not defined

Description
If you try to print it, error message will be generated as tuple no longer exists.

 

 

Lesson tags: accessing tuple elements, creating a tuple, deletion of tuple, slicing of tuple, traversing of tuple
Back to: Python Programming Tutorial