Tuple in Python
In Python, a tuple is an ordered collection of data or elements which are immutable, meaning you cannot add, remove, or modify elements from the tuple after they are created. Tuples are defined by enclosing a comma-separated sequence of elements within round brackets ( ).
Here's an example of a tuple that initializes a tuple called fruits containing five fruit strings:
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
Creating a Tuple
In Python, a tuple can be created by enclosing elements within round brackets.
Example:
subjects = ("Python", "Java", "Mongo", "Oracle", "MySQL")
nums = (21, 78, 34, 46, 11, 41, 57)
print(subjects)
print(nums)
Output:
('Python', 'Java', 'Mongo', 'Oracle', 'MySQL') (21, 78, 34, 46, 11, 41, 57)
A tuple can also be created using the tuple() constructor.
Example:
colors = tuple(("white", "green", "yellow", "blue", "red"))
print(colors)
Output:
('white', 'green', 'yellow', 'blue', 'red')
Accessing Tuple Elements
Elements in a tuple can be accessed by their index number, starting from 0 for the first element.
Example:
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print(fruits[2])
Output:
guava
Accessing Tuple Elements using Loop
You can access elements of a tuple using a for loop.
Example:
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
for i in fruits:
print(i)
Output:
mango grapes guava apple watermelon
Tuple Length
To get the length or size of a tuple, you can use the len() function.
Example:
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
print(len(fruits))
Output:
5
Concatenating Tuples
In Python, you can combine two or more tuples using the + operator.
Example:
fruits = ("mango", "grapes", "guava", "apple", "watermelon")
colors = ("white", "green", "yellow", "blue", "red")
tuples = fruits + colors
print(tuples)
Output:
('mango', 'grapes', 'guava', 'apple', 'watermelon', 'white', 'green', 'yellow', 'blue', 'red')