Python provides several built-in data structures that help you store and organize data efficiently. These include lists, tuples, sets, and dictionaries.
Ordered, changeable, and allows duplicate items.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
Ordered, unchangeable (immutable), and allows duplicates.
colors = ("red", "green", "blue")
Unordered, unchangeable (but you can add/remove items), and does not allow duplicates.
unique_numbers = {1, 2, 3, 4}
unique_numbers.add(5)
Unordered (as of Python 3.6+, now ordered), changeable, and stores data in key-value pairs.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person["name"])
Structure | Ordered | Mutable | Use Case |
---|---|---|---|
List | Yes | Yes | General-purpose data storage |
Tuple | Yes | No | Fixed data collections |
Set | No | Yes | Unique item storage |
Dictionary | Yes (3.7+) | Yes | Key-value mappings |
Choose the right data structure based on what you need—order, uniqueness, or fast access using keys.
Lists are ordered, mutable collections that can store multiple data types.
numbers = [1, 2, 3, 4, 5]
print(numbers)
Tuples are ordered, immutable collections.
numbers = (1, 2, 3)
print(numbers)
Dictionaries store key-value pairs.
person = {"name": "John", "age": 25}
print(person)
Sets store unique elements and support set operations.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B)
Set operations allow mathematical operations such as union, intersection, and difference.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A & B) # Intersection
print(A - B) # Difference
print(A ^ B) # Symmetric Difference
Sets support various methods for modification.
numbers = {1, 2, 3}
numbers.add(4)
numbers.remove(2)
numbers.discard(5)
numbers.clear()
print(numbers)