Namaste Coders!
In this article, we will learn about tuples in Python. Let's uncover the tuples.
What are tuples?
A tuple is a sequence of heterogeneous or homogeneous Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples are immutable i.e. they cannot be changed unlike lists and tuples use parentheses () , whereas lists use square brackets [].
# tuple in python
t=()
t1=tuple()
Pros of tuples over lists
- Lists are generally used for homogeneous datatypes. Since, tuples are quite similar to lists, both of them are used in similar situations as well. Tuples are immutable whereas lists are mutable.
- Iterating through tuple is faster than with list. So there is a slight performance boost.
- Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
- If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.
- Tuples take less memory space as compared to the lists.
Concatenating Tuple
We can concatenate tuple by using ‘+’ operator.
t1=(1,2,3,4,5)
t2=(6,7,8)
print(t1+t2)
# (1, 2, 3, 4, 5, 6, 7, 8)
Nesting of tuples
We can provide 2-D tuples by nesting one inside another.
t=((1,2,3,4),(5,6,0,7))
print(t) # ((1, 2, 3, 4), (5, 6, 0, 7))
print(t[0]) # (1, 2, 3, 4)
print(t[0][1]) # 2
To repeat a value inside a tuple we use (*) operator.
t=("python",)*3
print(t)
# ('python', 'python', 'python')
Immutable Tuples
Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable data type like list, its nested items can be changed.
t=(1,2,3,5,6)
t[4]=86
print(t)
Error
Traceback (most recent call last): File "c:/Users/meenu garg/Desktop/Python/PythonCodes/datatype/tuple.py", line 15, in t[4]=86 TypeError: 'tuple' object does not support item assignment
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple. But deleting a tuple entirely is possible using the keyword del.
t=(1,2,3,5,6)
del t
print(t)
It will show nameError
Traceback (most recent call last): File "c:/Users/meenu garg/Desktop/Python/PythonCodes/datatype/tuple.py", line 16, in print(t) NameError: name 't' is not defined
Functions in tuple
t=(1,2,3,5,6)
# length of a tuple
length=len(t)
print("length is ",length) # length is 5
# max of a tuple
maximum=max(t)
print("maximum is ",maximum) # maximum is 6
# min of a tuple
minimum=min(t)
print("minimum is ",minimum) # minimum is 1
# converting list into a tuple
l=[1,2,3,4,5]
t=tuple(l)
print(type(t)) # <class 'tuple'>
print(t) # (1, 2, 3, 4, 5)
The End
I hope you enjoyed the article and had a good learning experience.
Follow for more articles and keep sharing👩
Keep coding