()
.# Creating an empty tuple
tuple1 = ()
print(tuple1)
# Creating a tuple with a single element
tuple1 = (20.34,)
print(tuple1)
# Creating a tuple with multiple elements
tuple1 = 20.34, 2, "Python"
print(tuple1)
# Using round brackets explicitly
tuple1 = (20.34, 2, "Python")
print(tuple1)
Output:()
(20.34,)
(20.34, 2, 'Python')
(20.34, 2, 'Python')
Note: For a tuple with one element, a trailing comma is mandatory. Without it, Python treats the value as a single data type instead of a tuple.tuple()
method:# Creating a tuple using tuple()
a = tuple((38, 4.9, "FACE Prep"))
print(a)
Output:(38, 4.9, 'FACE Prep')
# Creating a nested tuple
tuple1 = (10, (20, 30))
print(tuple1)
# Nested tuple with two individual tuples
tuple1 = (10, 20)
tuple2 = ("Python",)
tuple3 = (tuple1, tuple2)
print(tuple3)
Output:(10, (20, 30))
((10, 20), 'Python')
[]
. Python supports both positive and negative indexing:# Accessing an element of a tuple
tuple1 = ("Python", 10, 20.3)
print(tuple1[1])
# Using negative indexing
tuple1 = (30, "Python", 30.34)
print(tuple1[-3])
# Accessing nested tuple elements
tuple1 = (("Welcome", 10, 20.3), (20, "Hai"))
print(tuple1[0][2])
print(tuple1[1][0])
Output:10
30
20.3
20
:
to access a range of elements:# Accessing a range of elements
tuple1 = (30, "Python", 30.34, 60)
print(tuple1[1:3])
# Accessing the entire tuple starting from index 1
tuple1 = (30, "Python", 30.34, 40, 20.24)
print(tuple1[1:])
Output:('Python', 30.34)
('Python', 30.34, 40, 20.24)
# Trying to modify an element
tuple1 = (30, "Python", 30.34, 40, 20.24)
tuple1[2] = "Hai"
Output:Traceback (most recent call last):
TypeError: 'tuple' object does not support item assignment
However, if a tuple contains a mutable element (e.g., a list), that element can be modified:# Modifying a mutable element
tuple1 = (30, "Python", [30.34, 40, 20.24])
tuple1[2][0] = "Hai"
print(tuple1)
Output:(30, 'Python', ['Hai', 40, 20.24])
# Reassigning a tuple
tuple1 = (30, "Python", 30.34, 40, 20.24)
tuple1 = (20, 1.45, "FACE Prep")
print(tuple1)
Output:(20, 1.45, 'FACE Prep')
+
operator:# Concatenating tuples
tuple1 = (30, "Python", 30.34)
tuple2 = (20, 1.45, "FACE Prep")
print(tuple1 + tuple2)
Output:(30, 'Python', 30.34, 20, 1.45, 'FACE Prep')
*
operator:# Repeating tuple elements
tuple1 = (30, "Python", 30.34)
print(tuple1 * 2)
Output:(30, 'Python', 30.34, 30, 'Python', 30.34)
in
and not in
:# Membership test
tuple1 = (30, "Python", 30.34)
print(30 in tuple1)
print("faceprep" in tuple1)
Output:True
False
count()
and index()
:# Using tuple methods
tuple1 = (30, "Python", 30.34, 30)
print(tuple1.count(30)) # Counts occurrences of 30
print(tuple1.index("Python")) # Finds index of 'Python'
Output:2
1