- Tuple is exactly same as list except that it is immutable. i.e. once we creates tuple object, we cannot perform any changes in that object. hence tuple is read only version of list.
Properties
- Insertion order is preserved.
- Duplicates are allowed.
- Heterogeneous objects are allowed.
Remark
- If our data is fixed and never changes then we should go for tuple.
- We can preserve insertion order and we can differentiate duplicate objects by using index. hence index will play very important role in tuple.
- +ve index ⇒ Forward direction (from left to right).
- -ve index ⇒ Backward direction (from right to left).
- We can represent tuple elements within parenthesis and with comma separator. Parenthesis are optional but recommended to use.
Example
Python
t=10,20,30,40
print(t)
print(type(t))
Output
PowerShell
(10, 20, 30, 40)
<class 'tuple'>
Note
- We have to take special care about single valued tuple. Compulsory the value should ends with comma, otherwise it is not treated as tuple.
Example
Python
t=(10)
print(t)
print(type(t))
Output
Python
10
<class 'int'>
Example
Python
t=(10,)
print(t)
print(type(t))
Output
Python
(10,)
<class 'tuple'>
Question
Which of the following are valid tuples?
Python
t=()
t=10,20,30,40
t=10
t=10,
t=(10)
t=(10,)
t=(10,20,30,40)
Answer
Python
t=() ✔
t=10,20,30,40 ✔
t=10 ❌
t=10, ✔
t=(10) ❌
t=(10,) ✔
t=(10,20,30,40) ✔
Tuple creation
- There are four methods to create tuple.
t=()
- Creation of empty tuple.
Example
Python
my_tuple = ()
print(my_tuple)
print(type(my_tuple))
Output
PowerShell
()
<class 'tuple'>
t = (element,) or t = element,
- Creation of single valued tuple, parenthesis are optional, should ends with comma.
Example
Python
my_tuple = (10,)
print(my_tuple)
print(type(my_tuple))
my_tuple = 10,
print(my_tuple)
print(type(my_tuple))
Output
PowerShell
(10,)
<class 'tuple'>
(10,)
<class 'tuple'>
t = (element1, element2,) or t = element1, element2,
- Creation of multi values tuples.
Example
Python
my_tuple = (10,20)
print(my_tuple)
print(type(my_tuple))
my_tuple = 10,20
print(my_tuple)
print(type(my_tuple))
Output
PowerShell
(10, 20)
<class 'tuple'>
(10, 20)
<class 'tuple'>
Using tuple() function
Example
Python
list=[10,20,30]
t=tuple(list)
print(t)
t=tuple(range(10,20,2))
print(t)
Output
Python
(10, 20, 30)
(10, 12, 14, 16, 18)
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!