Loading...

My Learning Pad Login

Welcome

PCEP-30-02 Module 3: Data Collections


Table of Contents

  1. Overview & Syllabus
  2. Lists
    • Introduction, Creation, and Features
    • Indexing and Slicing
    • List Methods and Functions
    • List Comprehensions
    • Nested Lists
    • Iteration, Membership, and Copying
    • Exercises
  3. Tuples
    • Introduction, Creation, and Immutability
    • Indexing and Slicing
    • Tuple Packing & Unpacking
    • Comparison with Lists
    • Exercises
  4. Dictionaries
    • Introduction, Creation, and Features
    • Adding, Removing, and Updating Items
    • Dictionary Methods
    • Iterating Keys and Values
    • Membership Checks
    • Nested Dictionaries
    • Exercises
  5. Strings
    • Construction, Indexing, and Slicing
    • Immutability and Escaping
    • String Methods
    • String Formatting
    • Exercises
  6. Practice Problems
  7. Summary Table

1. Overview & Syllabus

Module 3 covers knowledge and skills for processing and manipulating data using:


2. Lists

Introduction & Creating Lists

fruits = ["apple", "banana", "cherry"]
        numbers = list((1, 2, 3, 4))
        mixed = [1, "hi", 3.14, [2, 4]]
        

Indexing and Slicing

fruits = ["apple", "banana", "cherry"]
        print(fruits[0])   # apple
        print(fruits[-1])  # cherry
        print(fruits[1:3]) # ['banana', 'cherry']
        

List Methods and Functions

numbers = [4, 2, 1]
        numbers.append(7)   # Add to end
        numbers.insert(1, 5) # Insert at index 1
        numbers.remove(2)   # Remove first occurrence of 2
        print(numbers.index(4)) # Find index of 4
        more = numbers.copy() # Shallow copy
        print(len(numbers), sorted(numbers), min(numbers), max(numbers))
        # del instruction
        # del numbers[0]  # Remove item by index
        

List Comprehensions

squares = [x ** 2 for x in range(5)]  # [0, 1, 4, 9, 16]
        evens = [x for x in range(10) if x % 2 == 0]
        

Nested Lists

matrix = [[1,2,3], [4,5,6], [7,8,9]]
        print(matrix[1])    # [4, 5, 6]
        print(matrix[1][2]) # 6
        

Iteration, Membership, Copying

for fruit in fruits:
            print(fruit)
        if "banana" in fruits:
            print("Found!")
        cloned = fruits[:]
        

List Exercises

  1. Create a list of first 10 cubes using a list comprehension.
  2. Write a function that removes duplicates from a list.
  3. Write code to sum only the even numbers in a list.
  4. Reverse a list without using the reverse() method or slicing.

3. Tuples

Introduction, Creation, Immutability

t1 = (1, 2, "hi")
        t2 = tuple([3, 4, 5])
        single = (7,)  # Singleton tuple
        

Indexing and Slicing

coords = (2, 5, 8)
        print(coords[0])
        print(coords[1:])
        

Tuple Packing & Unpacking

a, b, c = (5, 6, 7)  # Unpacking
        t = (a, b, c)        # Packing
        

Comparison with Lists

Tuple Exercises

  1. Write a function to swap two values using tuple unpacking.
  2. Iterate through a tuple and print all values greater than a user input.
  3. Count the number of unique items in a tuple.

4. Dictionaries

Introduction, Creation, Features

person = {"name": "Tom", "age": 25}
        empty = dict()
        fromkeys = dict.fromkeys(["a", "b"], 0)
        

Adding, Removing, Updating Items

person["city"] = "London"
        person["age"] = 26
        removed = person.pop("name")
        del person["age"]
        

Dictionary Methods

print(person.keys())
        print(person.values())
        print(person.items())
        person.clear()
        

Iterating Keys, Values, Existence Checks

for key in person:
            print(key, person[key])
        for k, v in person.items():
            print(k, v)
        if "city" in person:
            print("City exists!")
        

Nested Dictionaries

data = {"A": {"score": 90}, "B": {"score": 85}}
        print(data["A"]["score"])
        

Dictionary Exercises

  1. Write a function that inverts keys/values of a dictionary.
  2. Count frequency of each letter in a string using a dictionary.
  3. Merge two dictionaries. If duplicate keys, prefer values from the second.
  4. Create a nested dictionary to represent a gradebook.

5. Strings

Construction, Indexing, Slicing

s = "Python"
        print(s[0], s[-1])
        print(s[2:5])
        

Immutability, Escaping, Multiline

t = "He said: "Hi!""
        multi = """This is
        multi-line"""
        

String Methods

msg = "  Hello, World!  "
        msg_lower = msg.lower()
        msg_strip = msg.strip()
        count_l = msg.count("l")
        words = msg.split()
        joined = "-".join(["a", "b", "c"])
        found = msg.find("World")
        

String Formatting

name = "Jane"
        age = 23
        output = f"{name} is {age} years old."  # f-strings
        output2 = "{} is {} years old.".format(name, age)
        

String Exercises

  1. Write a function to count the number of words in a string.
  2. Reverse a string using slicing and with a for loop.
  3. Check if a string is a palindrome.
  4. Find the most frequent character in a string.

6. Practice Problems

  1. Combine a list of names and a list of ages into a dictionary (name:age pairs).
  2. Write a program that checks if two tuples have any elements in common.
  3. Write a function that accepts any sequence (list, tuple, or string) and returns the unique elements in it.
  4. Write a list comprehension to find all uppercase letters in a string.
  5. Write a program that flattens a nested list (1-level deep).

7. Summary Table

Concept Syntax Example Notes
List mylist = [1, 2, 3] Mutable, ordered
Tuple mytuple = (1, 2, 3) Immutable, ordered
Dictionary mydict = {"a": 1, "b": 2} Key-value pairs, keys unique
String s = "hello" Immutable, sequence of characters
Slicing s[1:4], mylist[::-1] Get/reverse part(s)
Membership 'a' in mylist, 'x' not in s Check existence
Comprehension [x*2 for x in mylist] Compact loop/condition syntax
Nested arr = [[1,2],[3,4]] List of lists (matrices)
Dict Methods d.keys(), d.items(), d.get() Work with dict keys/values
Str Methods s.strip(), s.find('a') Remove space, search character