Python Collections
In Python, collections are ways to store multiple values in a single variable. Imagine a box where you can keep many items together – that’s what collections help you do in programming.
In Python, collections are ways to store multiple values in a single variable. Imagine a box where you can keep many items together – that’s what collections help you do in programming.
Python has four main types of collections:
Lists let you store multiple items in one variable. You can change, add, or remove items.
fruits = ["apple", "banana", "cherry"]
print(fruits)
['apple', 'banana', 'cherry']
Why this output? The list keeps all three fruits in the order they were added. The square brackets [] show it’s a list.
Tuples are like lists, but you can’t change them once created.
colors = ("red", "green", "blue")
print(colors)
('red', 'green', 'blue')
Why this output? The items are inside parentheses (), showing it’s a tuple. The order is kept, but the values can’t be changed later.
Sets store items without any duplicates and without keeping order.
numbers = {1, 2, 3, 2, 1}
print(numbers)
{1, 2, 3}
Why this output? Sets remove duplicates automatically. The numbers 2 and 1 appeared twice but are shown only once. The order may vary each time you run the code.
Dictionaries store data in a key: value format. Each key is unique and helps you find its value.
student = {"name": "Alice", "age": 20}
print(student)
{'name': 'Alice', 'age': 20}
Why this output? The dictionary keeps two key-value pairs. The keys "name" and "age" point to their respective values.
| Type | Ordered? | Changeable? | Duplicates Allowed? | Syntax |
|---|---|---|---|---|
| List | Yes | Yes | Yes | [ ] |
| Tuple | Yes | No | Yes | ( ) |
| Set | No | Yes | No | { } |
| Dictionary | No (but keys are read in insertion order) | Yes | No (keys must be unique) | { key: value } |