Tuples in Python
A tuple in Python is an ordered, immutable collection of elements. Tuples are
similar to lists but cannot be modified after creation. They are useful when you want to
ensure that data remains constant throughout the program.
Use Cases:
Storing fixed data like coordinates, RGB values, or configuration settings.
Returning multiple values from a function.
Using as keys in dictionaries (since tuples are hashable).
Ensuring data integrity by preventing accidental modification
t1 = (1, 2, 3)
t2 = ('a', 'b', 'c')
Key Characteristics
Ordered: Elements maintain their position and can be accessed via index.
Immutable: Once created, elements cannot be changed, added, or removed.
Heterogeneous: Can contain elements of different data types.
Indexed: Supports indexing and slicing like lists.
Creating a Tuple
Tuples are created using parentheses () and separating elements with commas.
t1 = (1, 2, 3, 4, 5)
t2 = ('a', 'b', 'c', 'd', 'c')
We can also create a tuple without parentheses:
t3 = 10, 20, 30
For a single-element tuple, include a trailing comma:
t4 = (5,) # Not just (5)
Tuple Operations
Operation Syntax / Method Description
Indexing tuple[index] Accesses element at a specific index
Slicing tuple[start:end] Returns a sub-tuple
Concatenation tuple1 + tuple2 Combines two tuples
Repetition tuple * n Repeats the tuple n times
Membership in, not in Checks if an element exists
Length len(tuple) Returns number of elements
Count tuple.count(value) Counts occurrences of a value
Index tuple.index(value) Finds the first index of a value
Example:
print("\t\t\t------")
print("\t\t\tTUPLES")
print("\t\t\t------")
t1=(1,2,3,4,5)
t2=('a','b','c','d','c')
print("1.Creating a tuple")
print(t1,t2)
print("")
print("2.Accessing by index")
print("Element at 3 in t1 : ",t1[3])
print("Element at 2 in t2 : ",t2[2])
print("")
print("3.Slicing a tuple")
print("After Slicing t1 [1:3] : ",t1[1:3])
print("After Slicing t2 [0:2] : ",t2[0:2])
print("")
print("4.Concatenation")
print("After concatenating t1 and t2 : ",t1+t2)
print("")
print("5.Repitition")
print("After repeating t1 (2 times) : ",t1*2)
print("After repeating t2 (3 times) : ",t2*3)
print("")
print("5.Using IN and NOT IN")
print("Is 5 in t1 : ",5 in t1)
print("Is 7 in t1 : ",7 in t1)
print("Is a not in t2 : ",'a' not in t2)
print("Is p not in t2 : ",'p' not in t2)
.Output:
------
TUPLES
------
1.Creating a tuple
(1, 2, 3, 4, 5) ('a', 'b', 'c', 'd', 'c')
2.Accessing by index
Element at 3 in t1 : 4
Element at 2 in t2 : c
3.Slicing a tuple
After Slicing t1 [1:3] : (2, 3)
After Slicing t2 [0:2] : ('a', 'b')
4.Concatenation
After concatenating t1 and t2 : (1, 2, 3, 4, 5, 'a', 'b',
'c', 'd', 'c')
5.Repitition
After repeating t1 (2 times) : (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
After repeating t2 (3 times) : ('a', 'b', 'c', 'd', 'c', 'a',
'b', 'c', 'd', 'c', 'a', 'b', 'c', 'd', 'c')
5.Using IN and NOT IN
Is 5 in t1 : True
Is 7 in t1 : False
Is a not in t2 : False
Is p not in t2 : True