Tuples in Python


 Tuple 

             Tuple is an ordered collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type and they are indexed by integers. The important difference between a list and a tuple that tuples are immutable. Its represented by tuple class.


Creating a tuple

              In Python tuples are created by placing sequence of values separated by 'comma' with or without the use of parentheses. Tuple can contain any number of elements and of any data type like strings, integers, list etc.

             

Note :  Creation of Python tuple without the use of parentheses is known as "Tuple Packing".

A tuple can be defined as follows :-

  1. Tuple1 = (101"Peter"22)    
  2. Tuple2 = ("Apple""Banana""Orange")     
  3. Tuple3 = 10,20,30,40,50  
  4.   
  5. print(type(Tuple1))  
  6. print(type(Tuple2))  
  7. print(type(Tuple3))  



Output :
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

Example

# creating an empty tuple
  tuple=()
  print(tuple)
# creating a tuple with the use of strings
  tuple=('btech','second','year')
  print(tuple)
# creating a tuple with the use of list
  list=[1,2,3,4,5]
  print(tuple(list))
#creating a tuple with the use of built-in function
  tuple=tuple('btech')
  print(tuple)


Output 

()

('btech','second','year')

(1,2,3,4,5)

('b','t','e','c','h')


Accessing element of a tuple

In order to access tuple item refer to the index number. use the index operator [] to access an item in a tuple. The index must be an integer.


Example

tuple=tuple([1,2,3,4,5])

print(tuple[-1])

print(tuple[1])

print(tuple[-3])


Output

5
2
3

Note : In Python, deletion or updation of a tuple is not allowed. This will cause an error because updating or deleting from a tuple is not supported. This is because tuples are immutable, hence element of a tuple cannot be changed once it has been assigned. Only new tuples can be reassigned to the same name.







1 comment: