Tuples in python
Tuples are used to store multiple items. 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 also have negative index number starting from [-1] from the last element of the tuple.
Example of tuple with numbers
tup=(10,20,30)
print(tup)
Output
(10, 20, 30)
Example of tuple with float
tup=(10.23,20.12,30.34,40.21,50.32)
print(tup)
Output
(10.23, 20.12, 30.34, 40.21, 50.32)
Example of tuple with string
tup=("python","c","c++","java","oracle")
print(tup)
Output
('python', 'c', 'c++', 'java', 'oracle')
Example of tuple containing values of different types
tup=(10,20.12,"python")
print(tup)
Output
(10, 20.12, 'python')
Example of tuple using for loop
tup=(10,20,30,40,50)
for i in tup:
print(i,end=' ')
Output
10 20 30 40 50
Example of tuple using positive index number
tup=(10,20,30,40,50)
print(tup[1])
Output
20
Example of tuple using negative index number
tup=(10,20,30,40,50)
print(tup[-1])
Output
50
Tuple slicing
Example1 of tuple slicing
tup=(10,20,30,40,50)
print(tup[1:4])
Output
(20, 30, 40)
Example2 of tuple slicing
tup=(10,20,30,40,50)
print(tup[:])
Output
(10, 20, 30, 40, 50)
Example3 of tuple slicing
tup=(10,20,30,40,50)
print(tup[2:])
Output
(30, 40, 50)
Example4 of tuple slicing
tup=(10,20,30,40,50)
print(tup[:4])
Output
(10, 20, 30, 40)
Example5 of tuple slicing
tup=(10,20,30,40,50)
print(tup[1:-2])
Output
(20, 30)