0% found this document useful (0 votes)
1 views11 pages

Module 7

This document provides lessons on lists and tuples in Python, covering their creation, access, modification, and common methods. It explains the differences between lists (mutable) and tuples (immutable), including practical examples and when to use each data structure. The content emphasizes the importance of lists and tuples in programming, particularly for storing and managing data.

Uploaded by

su4096012
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views11 pages

Module 7

This document provides lessons on lists and tuples in Python, covering their creation, access, modification, and common methods. It explains the differences between lists (mutable) and tuples (immutable), including practical examples and when to use each data structure. The content emphasizes the importance of lists and tuples in programming, particularly for storing and managing data.

Uploaded by

su4096012
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

In the name of Allah the most Beneficent and Merciful

JazakAllah to Maulana Haq Nawaz for composing these lessons

# ================================================

# Module 7 - Lesson 1: Lists

# ================================================

# Learn: Creating lists, accessing items, modifying,

# common list methods, looping over lists

# ================================================

print("=" * 50)

print("Lists — Storing Multiple Values")

print("=" * 50)

# ------------------------------------------------

# What is a List?

# ------------------------------------------------

# A list stores multiple values in one variable.

# Values are inside square brackets [ ] separated by commas.

# Each item has a position number called an index.

# Index starts at 0 (not 1).

# ------------------------------------------------

# 1. Creating a list

# ------------------------------------------------
print("\n1. Creating lists:")

prayers = ["Fajr", "Dhuhr", "Asr", "Maghrib", "Isha"]

marks = [85, 92, 78, 90, 88]

cities = ["Lahore", "Karachi", "Islamabad", "Peshawar"]

mixed = ["Ahmed", 15, "Lahore", True] # lists can mix types

print(prayers)

print(marks)

print(cities)

# ------------------------------------------------

# 2. Accessing items — index starts at 0

# ------------------------------------------------

print("\n2. Accessing items:")

print(prayers[0]) # Fajr (first item)

print(prayers[1]) # Dhuhr (second item)

print(prayers[4]) # Isha (fifth item)

print(prayers[-1]) # Isha (last item — negative index)

print(prayers[-2]) # Maghrib (second from last)

# Length of a list

print("Number of prayers:", len(prayers))

# ------------------------------------------------
# 3. Slicing — getting a portion of a list

# ------------------------------------------------

print("\n3. Slicing:")

print(prayers[0:3]) # first 3 items: Fajr, Dhuhr, Asr

print(prayers[2:]) # from index 2 to end

print(marks[:3]) # first 3 marks

# ------------------------------------------------

# 4. Modifying items

# ------------------------------------------------

print("\n4. Modifying:")

subjects = ["Quran", "Hadith", "Fiqh"]

print("Before:", subjects)

subjects[1] = "Tafseer" # change index 1

print("After:", subjects)

# ------------------------------------------------

# 5. Adding items

# ------------------------------------------------

print("\n5. Adding items:")

students = ["Ahmed", "Fatima"]

[Link]("Hassan") # add to end

print(students)
[Link](1, "Zainab") # insert at position 1

print(students)

# ------------------------------------------------

# 6. Removing items

# ------------------------------------------------

print("\n6. Removing items:")

fruits = ["mango", "apple", "banana", "guava"]

[Link]("apple") # remove by value

print(fruits)

[Link]() # remove last item

print(fruits)

[Link](0) # remove by index

print(fruits)

# ------------------------------------------------

# 7. Common list methods

# ------------------------------------------------

print("\n7. List methods:")

marks = [85, 42, 90, 55, 78]

print("Original :", marks)


print("Sorted :", sorted(marks)) # sorted() returns new list

print("Max :", max(marks))

print("Min :", min(marks))

print("Sum :", sum(marks))

print("Count :", len(marks))

print("Average :", sum(marks) / len(marks))

# Check if item exists

print("90 in marks:", 90 in marks)

print("100 in marks:", 100 in marks)

# ------------------------------------------------

# 8. Looping over a list

# ------------------------------------------------

print("\n8. Looping:")

for prayer in prayers:

print(f" - {prayer}")

print()

# Loop with index using enumerate

for i, prayer in enumerate(prayers, start=1):

print(f" {i}. {prayer}")

# ------------------------------------------------

# 9. Building a list from input


# ------------------------------------------------

print("\n9. Building from input:")

num = int(input("How many students? "))

student_names = []

for i in range(num):

name = input(f"Student {i+1} name: ")

student_names.append(name)

print("Class list:")

for i, name in enumerate(student_names, 1):

print(f" {i}. {name}")

print()

print("Lists are one of Python's most useful tools. Ma sha Allah!")

# ================================================

# Module 7 - Lesson 2: Tuples

# ================================================

# Learn: What tuples are, how they differ from lists,

# when to use them, tuple unpacking

# ================================================

print("=" * 50)

print("Tuples — Unchangeable Lists")

print("=" * 50)
# ------------------------------------------------

# What is a Tuple?

# ------------------------------------------------

# A tuple is like a list but IMMUTABLE — cannot be changed.

# Values are inside round brackets ( ) separated by commas.

# Use tuples for data that should never change:

# - Prayer times, days of week, compass directions

# - Coordinates, fixed settings, constants

# ------------------------------------------------

# 1. Creating a tuple

# ------------------------------------------------

print("\n1. Creating tuples:")

prayers = ("Fajr", "Dhuhr", "Asr", "Maghrib", "Isha")

days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday",

"Saturday", "Sunday")

coordinates = (31.5204, 74.3587) # Lahore coordinates

print(prayers)

print(days)

print(coordinates)

# ------------------------------------------------

# 2. Accessing items — same as lists


# ------------------------------------------------

print("\n2. Accessing:")

print(prayers[0]) # Fajr

print(prayers[-1]) # Isha

print(days[4]) # Friday

print("Length:", len(prayers))

# ------------------------------------------------

# 3. Tuples cannot be changed

# ------------------------------------------------

print("\n3. Tuples are immutable:")

# This would cause a TypeError — commented out to avoid crash:

# prayers[0] = "Tahajjud" # TypeError: 'tuple' object does not support item assignment

# This is WHY we use tuples — protect fixed data from accidental changes

print("Prayer names are fixed — tuples protect them.")

# ------------------------------------------------

# 4. Tuple unpacking — assign items to variables

# ------------------------------------------------

print("\n4. Tuple unpacking:")

# Assign each item in the tuple to a separate variable

first, second, third, fourth, fifth = prayers


print(f"First prayer : {first}")

print(f"Last prayer : {fifth}")

# Swap two variables using tuple unpacking

a = "Lahore"

b = "Karachi"

a, b = b, a # elegant swap — no temp variable needed!

print(f"After swap: a={a}, b={b}")

# Return multiple values from a function using tuple

def get_min_max(numbers):

return min(numbers), max(numbers) # returns a tuple

marks = [85, 42, 90, 55, 78]

lowest, highest = get_min_max(marks)

print(f"Lowest: {lowest}, Highest: {highest}")

# ------------------------------------------------

# 5. Looping over a tuple

# ------------------------------------------------

print("\n5. Looping:")

for i, prayer in enumerate(prayers, 1):

print(f" {i}. {prayer}")

# ------------------------------------------------
# 6. List vs Tuple — when to use which

# ------------------------------------------------

print("\n6. List vs Tuple:")

# Use LIST when data will change:

student_list = ["Ahmed", "Fatima"] # students join/leave

student_list.append("Hassan")

# Use TUPLE when data is fixed:

prayer_tuple = ("Fajr", "Dhuhr", "Asr", "Maghrib", "Isha")

print("List (changes allowed):", student_list)

print("Tuple (fixed forever) :", prayer_tuple)

# ------------------------------------------------

# 7. Practical example

# ------------------------------------------------

print("\n7. City coordinates:")

cities = [

("Lahore", 31.52, 74.36),

("Karachi", 24.86, 67.01),

("Islamabad", 33.72, 73.06),

("Peshawar", 34.01, 71.57),

]
for city, lat, lon in cities:

print(f"{city:<12}: Lat {lat}, Lon {lon}")

print()

print("Tuples protect data that should never change. Well done!")

You might also like