Collections are data types used to store multiple values in a single variable. They help us organize and manage data efficiently.
Python provides four commonly used collection types:
| Collection | Ordered | Allows Duplicates | Mutable |
|---|---|---|---|
| List | Yes | Yes | Yes |
| Tuple | Yes | Yes | No |
| Set | No | No | Yes |
| Dictionary | Yes | Keys: No | Yes |
# Mutable Example (List)
students = ["Shree", "Vinayak"]
students.append("Rohit")
print(students)
['Shree', 'Vinayak', 'Rohit']
# Immutable Example (Tuple)
students = ("Shree", "Vinayak")
students[0] = "Rohit"
TypeError:
'tuple' object does not support item assignment
A List is an ordered collection that can store multiple values. Lists are mutable, which means their contents can be modified.
students = ["Shree", "Vinayak", "Rohit"]
print(students)
['Shree', 'Vinayak', 'Rohit']
students = ["Shree", "Vinayak", "Rohit"]
print(students[0])
print(students[1])
Shree
Vinayak
students = ["Shree", "Vinayak"]
students.append("Rohit")
print(students)
['Shree', 'Vinayak', 'Rohit']
students = ["Shree", "Vinayak", "Rohit"]
for student in students:
print(student)
Shree
Vinayak
Rohit
A Tuple is an ordered collection used to store multiple values. Unlike Lists, Tuples are immutable, which means their values cannot be changed after creation.
students = ("Shree", "Vinayak", "Rohit")
print(students)
('Shree', 'Vinayak', 'Rohit')
students = ("Shree", "Vinayak", "Rohit")
print(students[0])
print(students[1])
Shree
Vinayak
students = ("Shree", "Vinayak", "Rohit")
students[0] = "Ram"
TypeError:
'tuple' object does not support item assignment
Note: Use Tuple when data should not be modified after creation.
A Set is an unordered collection of unique values. Duplicate values are automatically removed.
numbers = {10, 20, 30, 40}
print(numbers)
{10, 20, 30, 40}
numbers = {10, 20, 20, 30, 30, 40}
print(numbers)
{10, 20, 30, 40}
numbers = {10, 20, 30}
numbers.add(40)
print(numbers)
{10, 20, 30, 40}
numbers = {10, 20, 30}
for num in numbers:
print(num)
10
20
30
Note: Since Sets are unordered, the output order may vary.
A Dictionary stores data in key-value pairs. Each value is accessed using its corresponding key.
student = {
"name": "Shree",
"city": "Mumbai",
"age": 22
}
print(student)
{'name': 'Shree', 'city': 'Mumbai', 'age': 22}
student = {
"name": "Shree",
"city": "Mumbai"
}
print(student["name"])
print(student["city"])
Shree
Mumbai
student = {
"name": "Shree"
}
student["city"] = "Mumbai"
print(student)
{'name': 'Shree', 'city': 'Mumbai'}
student = {
"name": "Shree",
"city": "Mumbai"
}
for key, value in student.items():
print(key, value)
name Shree
city Mumbai
Note: Dictionaries are heavily used in Python and Django for storing structured data using key-value pairs.