Week 3 β€’ Python Course

Week 3: Lists, Tuples & GitHub

Master data collections, write elegant comprehensions, and collaborate remotely β€” all in one week.

πŸ“… Overview: Days 1–5 cover Python lists, tuples, and list comprehensions with a mini-project. Day 6 introduces GitHub for remote collaborationβ€”pushing, pulling, and cloning repositories. Each day includes concept explanations, live coding demos, student exercises, and solution discussions.

πŸ”— Prerequisite: Week 1 (variables, conditionals, git basics) & Week 2 (loops, git branching).

🎯 Goal: By the end of this week, you'll store and manipulate collections of data, write elegant one-line loops with comprehensions, and collaborate on GitHub remotely.

01

Lists Basics

create index slice
02
πŸ”§

List Methods

append insert remove sort
03
πŸ”’

Tuples

immutable unpack
04
⚑

Comprehen sions

concise loops if/else
05
πŸ“Š

Mini Project

gradebook CRUD
06
🌐

GitHub Remotes

push pull clone

Day 1 Lists: Creation, Indexing & Slicing

Learning Objectives: Understand what lists are. Create lists with different data types. Access items using positive and negative indexing. Slice lists to extract sublists. Use len() and in operator.

βœ‚οΈ List Slicing β€” Quick Reference Infographic
nums[1:4][1, 2, 3]
nums[:3][0, 1, 2]
nums[2:][2, 3, 4, 5]
nums[::2][0, 2, 4]
nums[::-1][5,4,3,2,1,0]

Creating Lists

day1_create.py
# Empty list
empty = []

# List of integers
numbers = [10, 20, 30, 40]

# Mixed data types
mixed = [1, "hello", 3.14, True]

# Nested list
matrix = [[1, 2], [3, 4]]

print(len(numbers))     # 4
print(10 in numbers)    # True

Indexing (positive & negative)

day1_indexing.py
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])      # apple  (first)
print(fruits[2])      # cherry (third)
print(fruits[-1])     # date   (last)
print(fruits[-2])     # cherry (second last)

Slicing Lists

day1_slicing.py
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])    # [1, 2, 3]   index 1 to 3
print(nums[:3])     # [0, 1, 2]   start to index 2
print(nums[2:])     # [2, 3, 4, 5] index 2 to end
print(nums[::2])    # [0, 2, 4]   every second element
print(nums[::-1])   # [5, 4, 3, 2, 1, 0]  reverse

πŸ§‘β€πŸ’» Exercise: Slice & Dice

Given the list colors = ["red", "green", "blue", "yellow", "purple"], write code to: 1) Print the first three colors. 2) Print the last two colors. 3) Print the list in reverse order.

day1_exercise_solution.py
colors = ["red", "green", "blue", "yellow", "purple"]
print(colors[:3])       # ['red', 'green', 'blue']
print(colors[-2:])      # ['yellow', 'purple']
print(colors[::-1])     # ['purple', 'yellow', 'blue', 'green', 'red']
πŸ’‘ Instructor Tip: Visualize a list as numbered boxes. The first box is index 0. Negative indices count from the right. Slicing always returns a new list; it does not modify the original.

Day 2 List Methods & Operations

Learning Objectives: Add, remove, and modify elements using list methods. Combine lists with + and extend(). Sort, reverse, and copy lists. Avoid common mutation pitfalls.

πŸ”§ List Methods β€” Quick Reference Infographic
append(x)Add to end
insert(i,x)Insert at i
remove(x)Remove first
pop(i)Remove & return
sort()Sort in place
reverse()Reverse
copy()Shallow copy
extend(lst)Add all

Adding & Removing Elements

day2_add_remove.py
fruits = ["apple", "banana"]
fruits.append("cherry")       # adds at end
fruits.insert(1, "mango")     # insert at index 1
fruits.remove("banana")       # removes first occurrence
popped = fruits.pop()         # removes last, returns it
fruits.pop(0)                 # removes index 0
del fruits[0]                 # deletes without returning
print(fruits)                 # []

Sorting, Reversing & Copying

day2_sort_copy.py
nums = [3, 1, 4, 1, 5, 9]
nums.sort()              # [1,1,3,4,5,9]
nums.sort(reverse=True)  # descending
nums.reverse()           # reverse current order

# Creating a true copy
original = [1, 2, 3]
copy1 = original.copy()
copy2 = original[:]
copy1.append(4)
print(original)   # [1,2,3] (unchanged)

Combining Lists

day2_combine.py
a = [1, 2]
b = [3, 4]
c = a + b            # [1,2,3,4] (new list)
a.extend(b)          # a becomes [1,2,3,4]
print(a)

πŸ§‘β€πŸ’» Exercise: Shopping List Manager

Create an empty list cart. Ask the user to add 3 items using append(). Then remove the second item using pop(). Finally sort the list and print it.

day2_exercise_solution.py
cart = []
cart.append(input("Item 1: "))
cart.append(input("Item 2: "))
cart.append(input("Item 3: "))
print("Cart before:", cart)
cart.pop(1)          # remove index 1
cart.sort()
print("Sorted cart:", cart)
Item 1: milk Item 2: eggs Item 3: bread Cart before: ['milk', 'eggs', 'bread'] Sorted cart: ['bread', 'milk']
⚠️ Beware of references: Assignment b = a does NOT copy a list; both point to the same object. Use .copy() or [:].

Day 3 Tuples: Immutable Sequences

Learning Objectives: Understand tuple immutability. Create tuples with and without parentheses. Access tuple items (indexing & slicing). Use tuple methods (count(), index()). Unpack tuples elegantly.

πŸ”’ Tuples vs Lists Infographic

πŸ“‹ List

  • Mutable β€” can be changed
  • Uses []
  • Slower, more memory
  • Cannot be dict keys

πŸ”’ Tuple

  • Immutable β€” fixed
  • Uses ()
  • Faster, less memory
  • Can be dict keys

Tuple Basics

day3_tuple_basics.py
# Creating tuples
empty = ()
single = (5,)          # comma required!
point = (3, 7)
coords = 10, 20        # packing

# Indexing works same as lists
print(point[0])        # 3
print(point[-1])       # 7

Immutability β€” Tuples Cannot Be Changed

day3_immutable.py
t = (1, 2, 3)
# t[0] = 10            # ❌ TypeError
# t.append(4)          # ❌ AttributeError

# Create new tuple by concatenation
t = t + (4, 5)          # (1,2,3,4,5)
print(t)

Tuple Methods & Unpacking

day3_unpacking.py
nums = (2, 4, 2, 6, 2)
print(nums.count(2))    # 3
print(nums.index(6))    # 3

# Tuple unpacking
point = (10, 20)
x, y = point            # 10 20

# Swapping variables
a, b = 5, 10
a, b = b, a             # 10 5

πŸ§‘β€πŸ’» Exercise: Student Record

Create a tuple student with (name, age, grade). Unpack it into three variables and print them. Then count how many 'A' grades in a list of tuples.

day3_exercise_solution.py
student = ("Riya", 14, "A")
name, age, grade = student
print(f"{name}, age {age}, grade {grade}")

students = [("Riya","A"),("Amit","B"),("Sara","A")]
a_count = sum(1 for _, g in students if g == "A")
print(f"Students with A grade: {a_count}")
πŸ’‘ Why tuples? Use tuples for data that shouldn't change. They are faster than lists and can be used as dictionary keys.

Day 4 List Comprehension

Learning Objectives: Write concise list transformations using comprehensions. Add conditional filtering (if) and if-else. Handle nested loops in comprehensions.

⚑ Anatomy of a List Comprehension Infographic

Hover each part to understand its role:

[x**2 for x in range(10) if x % 2 == 0]

Expression β†’ Iterator β†’ (optional) Condition

Basic Syntax

day4_basic_comp.py
# Traditional loop
squares = []
for i in range(1, 6):
    squares.append(i ** 2)

# List comprehension
squares_comp = [i ** 2 for i in range(1, 6)]
print(squares_comp)   # [1, 4, 9, 16, 25]

With Conditionals

day4_conditionals.py
# Filtering: only even numbers
evens = [x for x in range(1, 11) if x % 2 == 0]

# if-else inside expression
labels = ["even" if x % 2 == 0 else "odd" for x in range(1, 6)]
print(labels)  # ['odd','even','odd','even','odd']

Nested Loops in Comprehension

day4_nested_comp.py
# Coordinate pairs
pairs = [(x, y) for x in range(1, 3) for y in range(1, 3)]

# Multiplication table
table = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(table)   # [[1,2,3],[2,4,6],[3,6,9]]

πŸ§‘β€πŸ’» Exercise: Filter and Transform

Given nums = [5, 12, 17, 24, 35], create a new list with "high" if > 15 else "low".

day4_exercise_solution.py
nums = [5, 12, 17, 24, 35]
result = ["high" if n > 15 else "low" for n in nums]
print(result)   # ['low','low','high','high','high']
⚠️ Readability Note: If a comprehension is longer than ~70 characters or has complex logic, use a regular for loop instead.

Day 5 Mini-Project: Student Gradebook

Learning Objectives: Build a menu-driven program using lists and tuples. Store student records as tuples inside a list. Perform operations: add, view, average, find top student.

Project Requirements

  1. Store each student as a tuple: (name, marks).
  2. Provide a menu: 1. Add, 2. View all, 3. Average, 4. Top student, 5. Exit.
  3. Use while loop to keep running.
  4. Use list comprehension where possible.
gradebook.py
students = []

while True:
    print("\n--- Student Gradebook ---")
    print("1.Add 2.View 3.Average 4.Top 5.Exit")
    choice = input("Enter choice: ")

    if choice == '1':
        name = input("Name: ")
        marks = float(input("Marks: "))
        students.append((name, marks))
    elif choice == '2':
        for name, marks in students:
            print(f"{name}: {marks}")
    elif choice == '3':
        all_marks = [m for _, m in students]
        print(f"Avg: {sum(all_marks)/len(all_marks):.2f}")
    elif choice == '4':
        top = max(students, key=lambda s: s[1])
        print(f"Top: {top[0]} with {top[1]}")
    elif choice == '5':
        break
πŸš€ Extension: Add "Search by name", "Remove student", or store data in a file.

Day 6 GitHub: Push, Pull & Clone

Learning Objectives: Understand remote repositories. Connect a local Git repo to GitHub. Push code to GitHub. Pull changes from GitHub. Clone an existing GitHub repository.

🌐 GitHub Remote Workflow Visual
πŸ’» Local Repo
⬆️ push
☁️ GitHub
⬇️ pull
πŸ’» Local Repo

push = upload | pull = download | clone = copy entire repo

Essential GitHub Commands

CommandPurpose
git remote add origin <url>Link local repo to GitHub
git push -u origin mainUpload commits to GitHub
git pull origin mainDownload & merge from GitHub
git clone <url>Copy remote repo to computer

Pushing an Existing Project

terminal β€” first push
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/user/repo.git
git push -u origin main

Cloning a Repository

terminal β€” clone
git clone https://github.com/user/repo.git
cd repo
# Full project with Git history ready.
πŸ’‘ Pro Tips: Always git pull before starting work. Use git status frequently. Create branches for features and push them to GitHub.

Week 3 Practice Problems

πŸ”° Beginner Level

1. List Reverser
nums = [int(input(f"Number {i+1}: ")) for i in range(5)]
print("Reverse:", nums[::-1])
2. Remove Duplicates
lst = [1,2,2,3,1]
unique = []
for x in lst:
    if x not in unique: unique.append(x)
print(unique)
3. Tuple Swap
a, b = "first", "second"
a, b = b, a
print(a, b)

⚑ Intermediate Level

4. Flatten a Matrix
matrix = [[1,2],[3,4],[5,6]]
flat = [num for row in matrix for num in row]
print(flat)
5. Common Elements
a, b = [1,2,3,4], [3,4,5,6]
common = [x for x in a if x in b]
print(common)

Unsolved Exercises

πŸ”° Beginner

1. List Statistics

Ask for 5 numbers, store in list. Print sum, min, max, average.

Write your solution here.
2. Palindrome List Checker

Check if list reads same forwards and backwards.

Write your solution here.

⚑ Intermediate

3. Zip into Dictionary

Given keys and values lists, create a dictionary.

Write your solution here.
4. Matrix Transpose

Swap rows and columns using nested comprehension.

Write your solution here.