Collection
A group of related data items, such as a list of numbers, a set of names, or a dictionary of key-value pairs.
Collections are essential in computer science because they allow us to store, organise, and manipulate data efficiently.
Key Operations of Collections
- Addition: Inserting new items into the collection.
- Retrieval: Accessing items from the collection.
The retrieval operation is often called access or lookup in some programming languages.
NoteThe addition operation is often called insertion in some programming languages.
These operations are fundamental to working with collections and are supported by most programming languages.
| Collection type | Definition | Addition | Retrieval |
|---|---|---|---|
| List | An ordered collection of elements where duplicates are allowed. Each element has an index starting from 0. | Items can be added to the end or inserted at a specific index. | Items are accessed directly by their index (e.g., LIST[2]). |
| Set | An unordered collection of unique elements. No duplicates are allowed. | An item is added only if it is not already present. | Items cannot be accessed by index. They are retrieved by iterating through the set. |
| Dictionary (or Map) | A collection of key-value pairs where each key is unique and maps to a value. | Items are added as key–value pairs (e.g., DICT["name"] = "Ali"). | Items are retrieved by using their key (e.g., DICT["name"]). |
In Python, you can retrieve items from a dictionary using the key:
student_ages = {"Alice": 18, "Bob": 19, "Charlie": 20}
age = student_ages["Alice"] # Retrieves the age of Alice
print(age) # Output: 18 To add items to a list in Python, you can use the append() method:
students = ["Alice", "Bob", "Charlie"]
students.append("David") # Adds "David" to the end of the list
print(students) # Output: ["Alice", "Bob", "Charlie", "David"]