= ("apple", "banana", "mango")
fruits print(fruits)
print(type(fruits))
print(fruits[1])
('apple', 'banana', 'mango')
<class 'tuple'>
banana
A tuple is a collection of items just like a list; with one important difference that this collection is immutable. In other words, there is no option to add or remove elements form a tuple. A tuple can have elements of same data type or multiple data types. A tuple is denoted by parantheses (()
). A tuple can be initialized by putting a comma-separated collection of element within parantheses (or even with paranthesis). The tuple
keyword can be used to convert a list to a tuple. Note that when initializing a tuple with single element we need to put a comma after the element. To access an element by its index we can specify index in square brackets after the tuple name. A slice of a tuple returns a tuple.
= ("apple", "banana", "mango")
fruits print(fruits)
print(type(fruits))
print(fruits[1])
('apple', 'banana', 'mango')
<class 'tuple'>
banana
= "pineapple", "cherry"
fruits2 print(fruits2)
('pineapple', 'cherry')
= [1,2,3,4,5]
nums = tuple(nums)
nums_tuple print(nums_tuple)
(1, 2, 3, 4, 5)
Tuple can be concatenated in the same manner as strings are concatenated. The +
and *
operators can be used for tuple concatenation.
print(fruits+fruits2)
print(fruits2*3)
('apple', 'banana', 'mango', 'pineapple', 'cherry')
('pineapple', 'cherry', 'pineapple', 'cherry', 'pineapple', 'cherry')
Quiz: What would be the output of the following code. fruits = (“apple”, “mango”) fruits.append(“grapes”) print(fruits)
Error. Tuples are immutable.