Table of Contents
show
Introduction:
- A tuple is used to store sequence of items
- A tuple consists of items separated by commas
- Tuples are enclosed within parentheses rather than within square brackets
- A tuple is an immutable list i.e., once a tuple is created, one can’t add elements to a tuple or remove elements from the tuple
- Values in the tuple can be accessed by their index values.
Advantages
- Tuples are immutable i.e.; it is impossible to add / delete elements to / from a tuple
- Tuples are faster than lists, because they have a constant set of values
- Tuples can be used as dictionary keys, because they contain immutable values like strings, numbers
Creating a tuple
- To create a tuple, all the items are placed inside parentheses separated by commas and assigned to a variable
- The parenthesis, at the time of creating a tuple is not necessary but it is good to use parenthesis
- Tuples can have any number of data items (integer, float, string, list etc.)
- While creating a tuple with one element, add a final comma after the item or element in order to complete the assignment of the tuple
Tuple with integer data items
>>> ituple=(1,0,4,9,2)
>>> ituple
(1, 0, 4, 9, 2)
Tuple with items of different data items
>>> first_tuple =(1,"one",2.0,"three")
>>> print (first_tuple)
(1, 'one', 2.0, 'three')
Nested tuple
>>> ntuple = (3,2,4,[1,2.2],[4,5,6])
>>> ntuple
(3, 2, 4, [1, 2.2], [4, 5, 6])
Tuple can be created without parentheses
>>> wptuple= 4,5,6
>>> wptuple
(4, 5, 6)
Tuple with one item
>>> otuple=1
>>> type(otuple)
<class 'int'>
>>> otuple = 1,
>>> type(otuple)
<class 'tuple'>
Accessing values in tuples
Using Square brackets
Accessing the values in a tuple using the index number enclosed in square brackets along with the name of tuple
>>> first_tuple =(1,"one",2.0,"three")
>>> print(first_tuple[0])
1
>>> print(first_tuple[3])
three
>>> first_tuple[-1]
'three'
Using slicing operator
Slicing print the continuous value in tuple
>>> print(first_tuple[1:3])
('one', 2.0)
>>> first_tuple[-3:-1]
('one', 2.0)
>>> first_tuple[-4:-1:1]
(1, 'one', 2.0)
>>> first_tuple[-4:-1:2]
(1, 2.0)
>>> first_tuple[-1:-4:-2]
('three', 'one')
>>> print(first_tuple[-4:])
(1, 'one', 2.0, 'three')
>>> print(first_tuple[-4:-2])
(1, 'one')
Views: 0