This modue includes:


1. Tuples

A tuple is like a list but immutable—once created, you cannot change its elements:

# Create and concatenate
t = (1, 2)
t = t + (3, 4)
print(t)                 # → (1, 2, 3, 4)

# Indexing and slicing
print(t[0])              # → 1
print(t[-1])             # → 4
print(t[1:3])            # → (2, 3)

# Unpacking
x, y, *rest = t
print(x, y, rest)        # → 1 2 [3, 4]
# x gets the first value (1), y gets the second value (2),
# and *rest collects all the remaining values into a list → [3, 4].

Use cases: fixed configuration values, returning multiple values from functions, unpacking.


2. Dictionaries

A dictionary stores values indexed by unique keys (instead of by position):

# Create a dictionary of word frequencies
freq = {
    "the": 69033,
    "of":  36998,
    "and": 30157
}

# Lookup by key
print(freq["the"])        # → 69033

# Add or update entries
freq["to"] = 21892
freq["and"] = 30500       # overwrite old value

# Remove an entry
del freq["of"]

▷ Common methods

Looping over a dictionary yields its keys; We use .values() and .items() for values and (key, value) pairs:

  • dict.keys() → iterable of keys
  • dict.values() → iterable of values
  • dict.items() → iterable of (key, value) tuples
  • dict.get(key, default) → returns the value for a key, or default if the key is missing
for word in freq.keys():         #for word in freq:             
    print(word)      # Prints each key: "the", "and", "to"

for count in freq.values():   
    print(count)      # Prints each value: 69033, 30500, 21892

for word, count in freq.items():      
    print(f"{word}: {count}")   
    
print(freq.get("of", 0))    

3. More about functions

We learned function here. Functions help you DRY (“Don’t Repeat Yourself”) your code. They take arguments and may return values.

In addition to regular functions defined with def, Python also supports lambda functions, which are small anonymous functions defined in a single line. These are useful for short operations—especially when used with functions like map(), filter(), or sorted().

def greet(name):
    """Return a greeting for the given name."""
    return f"Hello, {name}!"

print(greet("Alice"))     # → "Hello, Alice!"

▷ Safe division

Avoid ZeroDivisionError by checking the denominator:

def safe_divide(a, b):
    """Divide a by b; return None if b is zero."""
    if b == 0:
        return None
    return a / b

print(safe_divide(10, 2))  # → 5.0
print(safe_divide(10, 0))  # → None

▷ Palindrome checker

def is_palindrome(s):
    """Return True if s reads the same forwards and backwards."""
    s = s.lower().replace(" ", "")
    return s == s[::-1]

print(is_palindrome("Race car"))  # → True
print(is_palindrome("Python"))    # → False

▷ Higher-order functions and lambdas

nums = [1, 2, 3, 4]                      

squares = list(map(lambda x: x**2, nums))   # lambda x: x**2 defines an anonymous function that squares x; map() applies that function to every element in 'nums'

print(squares)   # → [1, 4, 9, 16]                           

4. Classes

Functions let you group actions. Classes let you group both data and behaviors together. A class is like a blueprint for creating objects (instances) that have certain properties and can do certain things.

class Animal(object):                        # Define a class named Animal
    def __init__(self, species, age):       # Constructor: runs when you create an object
        self.species = species              # Instance variable
        self.age = age

    def is_person(self):                    # Method: like a function, but for the class
        return self.species

    def age_one_year(self):                 # Behavior: increase age by 1
        self.age += 1

You can also create a new class based on an existing one. This is called inheritance.

class Dog(Animal):                          # Dog inherits from Animal
    def age_one_year(self):                 # Overrides the method from Animal
        self.age += 7

▷ Simple test

a = Animal("Human", 5)
d = Dog("Dog", 5)

a.age_one_year()
d.age_one_year()

print(a.age)     # → 6 
print(d.age)     # → 12 

5. Working with files

In text data processing, you often need to save data to a file or read it back later. Python provides simple tools to handle plain text, CSV, and JSON formats.

▷ Write a file

data = ["apple", "banana", "cherry"]

with open("fruits.txt", "w", encoding="utf-8") as f:
    for fruit in data:
        f.write(fruit + "\n")

▷ Read from a text file

with open("fruits.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
print(lines)                    
# → ['apple\n', 'banana\n', 'cherry\n']

▷ Handling a CSV file

import csv

# Write CSV
with open("counts.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["word","count"])
    for w, c in freq.items():
        writer.writerow([w, c])

# Read CSV into a dictionary
counts = {}
with open("counts.csv", "r") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        counts[row["word"]] = int(row["count"])
print(counts)

▷ Handling a JSON file

import json

# Dump to JSON
with open("data.json", "w") as f:
    json.dump(freq, f, indent=2)

# Load from JSON
with open("data.json") as f:
    loaded = json.load(f)
print(loaded)

6. Exercises

  1. Phonebook dictionary

    • Create a dict phonebook mapping names to phone numbers.
    • Add, update, delete entries.
    • Print all entries in the format "Name: Number".
  2. Tuple swapping

    • Given a, b = 5, 10, swap their values in one line using tuple unpacking.
    • Print a and b after swapping.
  3. Function composition

    • Write a function apply_and_sum(func, lst) that applies func to each element of lst and returns the sum of results.
    • Test with func=lambda x: x*2 and lst=[1,2,3].
  4. Line counter

    • Write count_lines(filename) that returns the number of non-blank lines in a text file.
    • Use it on a sample .txt you create.
  5. CSV to JSON Converter

    • Write csv_to_json(csv_file, json_file) that reads csv_file (with headers) into a list of dicts and writes it as JSON to json_file.
    • Verify by loading the JSON and printing the first record.