Tuple Operations in
Python
In Python, a tuple is an immutable sequence of elements. Learn
how to create, access, modify, concatenate tuples, and more!
by RESHAM CHAUDHARI (23MEI10011)
SHIVENDRA DWIVEDI (23BAI10727)
AMRIT RAJ (23MEI10008)
VISHAL KUMAR (23MEI10012)
What is a Tuple?
A tuple is a collection of ordered and immutable
elements. It can contain different data types and is
enclosed within parentheses ().
EX.- tuple1=(1,2,3,4,5,6)
print(tuple1)
OUTPUT:-
(1,2,3,4,5,6)
Creating a Tuple
Syntax Tuple Constructor Packing
Use parentheses to Create a tuple using Assign multiple
define a tuple: the tuple() function: values to a tuple:
tuple1 = (1, my_tuple = x, y, z = 1, 2, 3
'apple', True) tuple(('a', 1,
[2, 3]))
Accessing Elements in a Tuple
Slicing
Indexing Negative Indexing
Retrieve a range of
Access individual elements :my_tuple=( Access elements
elements using index 1,2,3,4,5,6) from the end:
notation: my_tuple[0] print(my_tuple[1:4] my_tuple[-1]
)
Modifying Elements in a Tuple
Tuples are immutable, meaning their elements cannot be modified. However, you can cre
1 Create a New Tuple 2 Convert to List
Combine tuples using Convert the tuple to a list,
concatenation(+) or modify the list, and convert
slicing([:]) and it back to a tuple.
reassignment.
INPUT:
Tuple Concatenation
You can concatenate multiple tuples using the OUTPUT:
'+' operator: my_tuple = tuple1 + tuple2.
The result is a new tuple.
Tuple Unpacking
Assign Multiple Variables Ignore Unwanted Elements
Unpack elements of a tuple into Use an underscore (_) to ignore
separate variables: x, y, z = specific elements when
my_tuple. unpacking: x, _, z =
my_tuple.
Common Operations and
Methods on Tuples
1 Length
Get the number of elements in a tuple: len(my_tuple)
Ex- print(len(tuple1))
Membership
2 Check if an element is present in a tuple: element in my_tuple
Ex-if “2" in tuple1:
print("yes")
else:
print("no")
3 Count
Count the occurrences of an element: my_tuple.count(element)
EX-print(my_tuple.count(6))
4 Index
Find the index of the first occurrence of an element: my_tuple.index
EX-print(tuple1.index(“2"))