Category: python
Python Tuples
Published on 24 Jul 2026
Explanation
A tuple is an ordered and immutable collection in Python. Unlike lists, tuples cannot be modified after they are created.
Code:
student = ('John', 21, 'Computer Science', 89.5)
print(student)
print('Name:', student[0])
print('Age:', student[1])
print('Department:', student[2])
print('Marks:', student[3])
print('Last Element:', student[-1])
print('First Two Elements:', student[:2])
for item in student:
print(item)
Explanation
Although tuples are immutable, Python provides several useful operations for working with them. You can determine the length of a
Code:
numbers = (10, 20, 30, 20, 40)
print('Length:', len(numbers))
print('Count of 20:', numbers.count(20))
print('Index of 30:', numbers.index(30))
new_tuple = numbers + (50, 60)
print(new_tuple)
repeated = (1, 2) * 3
print(repeated)
name, age, city = ('Alice', 25, 'Chennai')
print(name)
print(age)
print(city)
Explanation
A set is an unordered collection of unique elements. Duplicate values are automatically removed. Sets are created using curly braces
Code:
fruits = {'Apple', 'Banana', 'Orange'}
fruits.add('Mango')
print(fruits)
fruits.remove('Banana')
print(fruits)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print('Union:', set1 | set2)
print('Intersection:', set1 & set2)
print('Difference:', set1 - set2)
print('Symmetric Difference:', set1 ^ set2)
Explanation
A dictionary is a collection of key-value pairs. Unlike lists and tuples, dictionary elements are accessed using keys instead of
Code:
student = {
'id': 101,
'name': 'John',
'age': 22,
'course': 'Python'
}
print(student)
print(student['name'])
print(student['course'])
print(student.keys())
print(student.values())
print(student.items())
Explanation
Python dictionaries can be modified by adding new key-value pairs or updating existing ones. The update() method modifies multiple values
Code:
employee = {
'id': 1001,
'name': 'Alice',
'department': 'IT',
'salary': 50000
}
employee['salary'] = 55000
employee['city'] = 'Chennai'
print(employee.get('department'))
employee.update({'experience': 5})
employee.pop('city')
for key, value in employee.items():
print(key, ':', value)