Python Tuples¶
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets ()
In [1]:
T = ()
print(T)
In [2]:
T = (10,3.14,"Machine Learning",98.34,100,"Python",77)
print(T)
- Tuple items are ordered, unchangeable, and allow duplicate values.
- Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
- Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
- Since tuple are indexed, tuples can have items with the same value:
In [3]:
T[0]
Out[3]:
Determine the length and type of a list¶
In [4]:
print(len(T))
In [5]:
print(type(T))
Access tuple items¶
- Tuple items are indexed and you can access them by referring to the index number:
- Negative indexing means start from the end.
- 1 refers to the last item, -2 refers to the second last item etc.
- You can specify a range of indexes by specifying where to start and where to end the range.
In [6]:
T = (10,3.14,"Machine Learning",98.34,100,"Python",77)
print(T)
print(T[:])
print(T[::])
print(T[0])
print(T[2:5])
print(T[2:])
print(T[:5])
print(T[-1])
print(T[-3:])
Change Tuple Values¶
- Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
- But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
In [7]:
print(T)
In [8]:
L = list(T)
L[1] = "Itronix Solutions"
T = tuple(L)
print(T)
Unpacking a tuple:¶
In [9]:
a,b,c = ('python',10,45.66)
print(a)
print(b)
print(c)
Loop Through a Tuple¶
- You can loop through the tuple items by using a for loop.
In [10]:
T = (10,3.14,"Machine Learning",98.34,100,"Python",77)
for item in T:
print(item)
Loop Through the Index Numbers¶
In [11]:
for i in range(len(T)):
print(L[i])
Print list items using while loop¶
In [12]:
for i in range(len(T)):
print(L[i])
Print list items using while loop¶
In [13]:
T = (10,3.14,"Machine Learning",98.34,100,"Python",77)
i=0
while i < len(T):
print(T[i])
i = i + 1
Join Two Tuples¶
In [14]:
T1 = (1,2,3)
T2 = (4,5,6)
T3 = T1 + T2
print(T3)
Multiply Tuples¶
In [15]:
T1 = (1,2,3)
print(T1 * 3)
Count item in Tuple¶
In [16]:
T1 = (1,45,35,78,35,67,45,25,78,45)
T1.count(45)
Out[16]:
Find index of a item in tuple¶
In [17]:
T1.index(35)
Out[17]: