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.
Lists Basics
List Methods
Tuples
Comprehen sions
Mini Project
GitHub Remotes
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.
Creating Lists
# 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)
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
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.
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']
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.
Adding & Removing Elements
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
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
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.
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)
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.
π 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
# 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
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
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.
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}")
Day 4 List Comprehension
Learning Objectives: Write concise list transformations using comprehensions. Add conditional filtering (if) and if-else. Handle nested loops in comprehensions.
Hover each part to understand its role:
Expression β Iterator β (optional) Condition
Basic Syntax
# 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
# 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
# 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".
nums = [5, 12, 17, 24, 35]
result = ["high" if n > 15 else "low" for n in nums]
print(result) # ['low','low','high','high','high']
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
- Store each student as a tuple: (name, marks).
- Provide a menu: 1. Add, 2. View all, 3. Average, 4. Top student, 5. Exit.
- Use
whileloop to keep running. - Use list comprehension where possible.
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
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.
push = upload | pull = download | clone = copy entire repo
Essential GitHub Commands
| Command | Purpose |
|---|---|
git remote add origin <url> | Link local repo to GitHub |
git push -u origin main | Upload commits to GitHub |
git pull origin main | Download & merge from GitHub |
git clone <url> | Copy remote repo to computer |
Pushing an Existing Project
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
git clone https://github.com/user/repo.git
cd repo
# Full project with Git history ready.
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.
2. Palindrome List Checker
Check if list reads same forwards and backwards.
β‘ Intermediate
3. Zip into Dictionary
Given keys and values lists, create a dictionary.
4. Matrix Transpose
Swap rows and columns using nested comprehension.