Python tuples are ordered collections of elements. They are immutable, which means elements of a tuple cannot be changed. We can store different types of elements in a tuple and access them using their index.
a. Creating a tuple: Tuples in Python can be created by placing the sequence inside the parentheses ( ).
Code
tuple1 = (1, 2, 3, 4, 5)
print(tuple1)
Output
b. Accessing elements in a tuple: We can access individual elements using indexing and a range of elements using slicing.
Code
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[0])
print(tuple1[2:4])
print(tuple1[:])
Output
c. Tuple operations: Python includes the following tuple operations - concatenation, repetition, membership.
Code
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
print(tuple1 + tuple2)
print(tuple1 * 3)
print(1 in tuple1)
print(1 in tuple2)
Output
(1, 2, 3, 4, 5)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
True
False
d. Tuple methods: Python includes the following built-in methods to work with tuples - count(), index().
Code
tuple1 = (1, 2, 2, 3, 3, 3)
print(tuple1.count(3))
print(tuple1.index(2))
Output
Enquiries
[email protected]
Copyright © 2023 - slash-root.com