Tuples
Tuples¶
- Tuples are used to store multiple items in a single variable.
- Tuples are immutable, meaning once created, their elements cannot be changed.
Tuple is Immutable¶
In [1]:
Copied!
my_tuple = (1, 2, 3)
my_tuple[0] = 5
# my_tuple[0] = 10 # This will raise an error
my_tuple = (1, 2, 3)
my_tuple[0] = 5
# my_tuple[0] = 10 # This will raise an error
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[1], line 2 1 my_tuple = (1, 2, 3) ----> 2 my_tuple[0] = 5 3 # my_tuple[0] = 10 # This will raise an error TypeError: 'tuple' object does not support item assignment
Indexing and Slicing¶
In [8]:
Copied!
t = ('a', 'b', 'c', 'd', 'e')
print(t[0]) # First element
print(t[-1]) # Last element
print(t[1:4]) # Slicing
print(t[::-1]) # Reversed
t = ('a', 'b', 'c', 'd', 'e')
print(t[0]) # First element
print(t[-1]) # Last element
print(t[1:4]) # Slicing
print(t[::-1]) # Reversed
a e ('b', 'c', 'd') ('e', 'd', 'c', 'b', 'a')
Tuple Methods¶
Method | Description | Example Code | Output |
---|---|---|---|
count() |
Returns the number of times a value appears | t = (1, 2, 1) t.count(1) |
2 |
index() |
Returns the index of the first matching value | t = (10, 20, 30) t.index(20) |
1 |
In [2]:
Copied!
my_tuple = ('apply', 'coco', 'sdfjh', 'mango')
my_tuple.index('coco')
my_tuple = ('apply', 'coco', 'sdfjh', 'mango')
my_tuple.index('coco')
Out[2]:
1
Exercise : Create a tuple of 5 artists.¶
- Print the first and last artists.
- Print a slice from second to fourth artists.
- Count a particular artists (create some duplicate in the tuple for this).
- Try modifying an element (and observe the error).
Unpacking a tuple¶
In [ ]:
Copied!
In [10]:
Copied!
country_1, country_2, country_3 = ('Nepal', 'Japan', 'India')
print(country_1)
print(country_2)
print(country_3)
country_1, country_2, country_3 = ('Nepal', 'Japan', 'India')
print(country_1)
print(country_2)
print(country_3)
Nepal Japan India
Add new element in Tuple¶
In [11]:
Copied!
t = ('a', 'b', 'c', 'd', 'e')
t = ('a', 'b', 'c', 'd', 'e')
In [ ]:
Copied!