← Back to Dashboard

Data Structures: Concept Notes

"""
Topic 05: Data Structures - Concept Notes

Python has four built-in data structures used to store collections of data.

1. List
   - Ordered, mutable (changeable), allows duplicates.
   - Syntax: [1, 2, "apple"]
   - Methods: append(), extend(), insert(), remove(), pop(), sort(), reverse().

2. Tuple
   - Ordered, immutable (unchangeable), allows duplicates.
   - Syntax: (1, 2, "apple")
   - Efficient for read-only data.

3. Set
   - Unordered, mutable, no duplicate members.
   - Syntax: {1, 2, "apple"}
   - Methods: add(), remove(), discard(), pop(), union(), intersection(), difference().

4. Dictionary
   - Ordered (as of 3.7+), mutable, key:value pairs.
   - No duplicate keys.
   - Syntax: {"name": "Alice", "age": 25}
   - Methods: keys(), values(), items(), get(), update(), pop().
"""

# 1. Lists & List Comprehensions
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
squares = [x**2 for x in range(5)] # List comprehension
print(f"Fruits: {fruits}")
print(f"Squares: {squares}")

# 2. Tuples
point = (10, 20)
# point[0] = 15 # Error! Tuples are immutable

# 3. Sets
odd_nums = {1, 3, 5, 7, 1} # Duplicate '1' is ignored
print(f"Set: {odd_nums}")

# 4. Dictionaries
user = {"name": "Bob", "id": 101}
user["email"] = "bob@example.com"
print(f"User Name: {user.get('name')}")

# Iterating over dictionary
for key, value in user.items():
    print(f"{key}: {value}")