3.3  Data structures

Data structures are containers that organize and store data in a specific layout, enabling efficient access and modification. Python offers powerful built-in structures and specialized external libraries like Pandas.

Lists

A list is an ordered, mutable (changeable) collection of items. They are the most flexible sequence type and are defined using square brackets []. Lists are ordered, which means that items maintain the order in which they were inserted. Lists are mutable, which means that you can add, remove and change items after creation. Duplicates are allowed, meaning that the same valuer can appear multiple times in a list.

grades = [90, 75, 90, 88] # Create a list
grades.append(95)         # Add an item (Mutate)
print(grades[0])          # Access item at index 0 (90)

Note that Python is a “zero-indexed” language, meaning that the first item is accessed at position [0].

Tuples

A tuple is an ordered, immutable (unchangeable) collection of items - where the same item can appear multiple times. They are often used for fixed collections of related data and are defined using parentheses (). Tuples are immutable, which means that you cannot change, add or remove items after creation.

coordinates = (10.5, 20.1)  # Create a tuple
# coordinates[0] = 5       # This would cause an error since tuples are immutable!
print(coordinates[0])       # Access item at index 0 (10.5)

Dictionaries

A dictionary is an ordered, mutable collection of unique key-value pairs. They are optimized for retrieving values based on a key and are defined using curly braces {}. The dictionary keys must be unique, which allows for fast lookups.

student = {
    "name": "Alex",
    "id": 101,
    "major": "Physics"
}
print(student["major"])    # Access value by the key: Physics (Performing a "lookup")
student["major"] = "Mechanical engineering" # Change the value ("Mutate")

Sets

A set is an unordered, mutable collection of unique items. They are typically used for checking membership and performing mathematical set operations (union, intersection). Like dictionaries, they are defined using curly braces {} (or set() for an empty set), but without keys. Sets are unordered, which means that items have no specific index. Duplicate elements in sets are automatically discarded.

numbers = {4, 2, 3, 3, 1} # Duplicates (the second '3') are ignored
print(numbers)            # Output: {1, 2, 3, 4}
numbers.add(5)
is_present = 3 in numbers # returns True since 3 is in numbers