What is tuple in python
A tuple in Python is an ordered collection of elements, similar to a list. Tuple is built-in data types in Python used to store collections of data. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
Syntax:
my_tuple = (1, 2, 3)
Or even without parentheses (though parentheses are recommended):
my_tuple = 1, 2, 3
Tuple Operations
- Indexing
print(t[0])
- Slicing
print(t[1:])
- Iteration
for item in t:
print(item)
Q: According to user choice enter some elements in tuple.
mytupule=() ch=int(input("enter elements")); for i in range(ch): a=int(input("enter a number")); mytupule=mytupule+(a,); print(mytupule);
Tuple Methods
Tuples have only 2 built-in methods:
my_tuple.count(2) # 2
my_tuple.index(3) # 2
# Creating Tuples
empty_tuple = ()
single_item = (42,)
multi_items = (1, 2, 3, 4)
print("Empty Tuple:", empty_tuple)
print("Single-item Tuple:", single_item)
print("Multi-item Tuple:", multi_items)
# Indexing and Slicing
print("First Element:", multi_items[0])
print("Slice [1:3]:", multi_items[1:3])
# Tuple with different data types
mixed_tuple = ("Python", 3.10, True)
print("Mixed Tuple:", mixed_tuple)
# Tuple Packing and Unpacking
person = ("Alice", 28, "Developer")
name, age, profession = person
print(f"Name: {name}, Age: {age}, Profession: {profession}")
# Extended Unpacking
a, *b = (10, 20, 30, 40)
print("a:", a) # 10
print("b:", b) # [20, 30, 40]
# Iterating over a tuple
print("Iterating over a tuple:")
for item in multi_items:
print(item)
# Membership test
print("Is 3 in multi_items?", 3 in multi_items)
# Length of tuple
print("Length of multi_items:", len(multi_items))
# Concatenation and Repetition
t1 = (1, 2)
t2 = (3, 4)
print("Concatenated Tuple:", t1 + t2)
print("Repeated Tuple:", t1 * 2)
# Tuple Methods
numbers = (1, 2, 3, 2, 4, 2)
print("Count of 2:", numbers.count(2))
print("Index of 3:", numbers.index(3))
# Nested Tuples
nested = (1, (2, 3), [4, 5])
print("Nested Tuple:", nested)
# Modifying mutable element inside tuple
nested[2].append(6)
print("Modified Nested Tuple:", nested)
0 Comments