Python Tuple

A tuple is a sequence of immutable objects, therefore tuple cannot be changed. It can be used to collect different types of object.

  The objects are enclosed within parenthesis and separated by comma.

  Tuple is similar to list. Only the difference is that list is enclosed between square bracket, tuple between parenthesis and List has mutable objects whereas Tuple has immutable objects.


Creating the Tuple


#empty tuple
tuple=()

#tuple of integers
tuple1=(1,2,3,4,5,6,7)

#tuple of name
tuple2=('Sachin','Ponting','ABD')

print(tuple)
print(tuple1)
print(tuple2)
()
(1, 2, 3, 4, 5, 6, 7)
('Sachin', 'Ponting', 'ABD')

NOTE : If Parenthesis is not given with a sequence, it is by default treated as Tuple.

Example of tuple without bracket


day='Monday', 'Tuesday', 'Wednesday'

print(day)
print("Length of day tuple is ",len(day))
('Monday', 'Tuesday', 'Wednesday')
Length of day tuple is  3

Concatenation of Tuples


numbers=1,2,3,4,5,6
day='Monday', 'Tuesday', 'Wednesday'
print(numbers)
print(day)
print("Concatenatiing two tuple ")
my_tuple=numbers+day
print(my_tuple)
print("length of new tuple is ",len(my_tuple))
(1, 2, 3, 4, 5, 6)
('Monday', 'Tuesday', 'Wednesday')
Concatenatiing two tuple
(1, 2, 3, 4, 5, 6, 'Monday', 'Tuesday', 'Wednesday')
length of new tuple is  9

Deleting a Tuple


numbers=1,2,3,4,5,6
del numbers # deleting the tuple  
print(numbers)
Traceback (most recent call last):
  File "Tuple.py", line 3, in 
    print(numbers)
NameError: name 'numbers' is not defined

del keyword is used for deleting the tuple

Converting list to a Tuple


numbers=list(range(11)) #creating list of sequence
print(numbers)
my_tuple=tuple(numbers)# converting list to tuple
print(my_tuple)
print("=======================")
print("Length of numbers list is ",len(numbers))
print("Length of my_tuple tuple is ",len(my_tuple))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
=======================
Length of numbers list is  11
Length of my_tuple tuple is  11

tuple(object) function is used to convert object to list

Advantages of using Tuple

  Tuples are more faster than Lists

  It makes the data safe as Tuples are immutable and hence cannot be changed.

woman avatar

What we are going to learn in Data Structure