Lists and Loops
Learn to work with collections of data and automate repetitive tasks. Lists, for loops, and if/else -- the patterns behind every AI application.
So far, you've worked with single pieces of data -- one name, one number. But real life involves collections. A class roster. A grocery list. A list of job openings. That's where lists come in.
And when you need to do something to every item in a list? That's where loops come in.
Lists: Collections of Things
A list in Python holds multiple items in order. You create one with square brackets:
neighborhoods = ["West Side", "South Side", "East Side", "Downtown", "North Side"]
print(neighborhoods)
Output: ['West Side', 'South Side', 'East Side', 'Downtown', 'North Side']
You can put anything in a list -- text, numbers, or even a mix:
scores = [85, 92, 78, 95, 88]
mix = ["Maria", 28, "San Antonio", True]
Accessing List Items
Each item has a position number called an index. Python starts counting at 0, not 1. This trips up everyone at first.
neighborhoods = ["West Side", "South Side", "East Side", "Downtown", "North Side"]
print(neighborhoods[0]) # West Side
print(neighborhoods[1]) # South Side
print(neighborhoods[4]) # North Side
print(neighborhoods[-1]) # North Side (last item)
Changing Lists
Lists are flexible. You can add, remove, and change items:
skills = ["Excel", "Google Docs", "Email"]
print(f"Starting skills: {skills}")
# Add a skill
skills.append("Python")
print(f"After learning Python: {skills}")
# Add another
skills.append("AI Prompting")
print(f"After AI module: {skills}")
# How many skills?
print(f"Total skills: {len(skills)}")
For Loops: Do Something for Every Item
A for loop runs the same code for each item in a list. This is where things get powerful.
participants = ["Maria", "Carlos", "Destiny", "Juan", "Aisha"]
for person in participants:
print(f"Welcome to the AI course, {person}!")
Output:
Welcome to the AI course, Maria!
Welcome to the AI course, Carlos!
Welcome to the AI course, Destiny!
Welcome to the AI course, Juan!
Welcome to the AI course, Aisha!
The loop takes each name from the list, puts it in the variable person, and runs the indented code. Then it moves to the next name. The indentation (4 spaces) tells Python what code belongs inside the loop.
Here's a practical example -- calculating total hours:
daily_hours = [8, 7.5, 8, 6, 8, 0, 0] # Mon through Sun
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
total = 0
for hours in daily_hours:
total = total + hours
print(f"Total weekly hours: {total}")
print(f"Average daily hours: {total / 7:.1f}")
If/Else: Making Decisions
Sometimes your code needs to make decisions. That's what if/else does:
temperature = 98 # Pretty normal for San Antonio summers
if temperature > 95:
print("It's hot out there! Stay hydrated.")
elif temperature > 80:
print("Nice and warm today.")
elif temperature > 60:
print("Mild weather -- enjoy it!")
else:
print("Bundle up! (rare in San Antonio)")
elif means "else if" -- it checks the next condition if the previous one wasn't true. else catches everything that didn't match.
Combining Loops and If/Else
This is where it gets real. You can use if/else inside a loop to process data intelligently:
scores = [85, 42, 91, 67, 73, 55, 88, 96, 38, 71]
passing = 0
failing = 0
for score in scores:
if score >= 70:
passing = passing + 1
else:
failing = failing + 1
total = passing + failing
pass_rate = (passing / total) * 100
print(f"Total students: {total}")
print(f"Passing: {passing}")
print(f"Failing: {failing}")
print(f"Pass rate: {pass_rate}%")
Here's another example that's closer to what you'd do in a real job:
applicants = [
{"name": "Maria", "experience": 3, "has_certification": True},
{"name": "Carlos", "experience": 1, "has_certification": False},
{"name": "Destiny", "experience": 5, "has_certification": True},
{"name": "Juan", "experience": 2, "has_certification": True},
]
print("--- Qualified Applicants ---")
for person in applicants:
if person["experience"] >= 2 and person["has_certification"]:
print(f" {person['name']} - {person['experience']} years experience")
This loops through applicants and only prints the ones who meet both criteria. This is the same basic logic that job screening software uses (which is why understanding bias from Module 5 matters so much).
Range: Loops with Numbers
Sometimes you want to loop a specific number of times:
# Count from 1 to 5
for i in range(1, 6):
print(f"Step {i} of 5")
range(1, 6) gives you numbers 1, 2, 3, 4, 5. The second number is excluded (another Python quirk you'll get used to).
A Real Mini-Project
Let's combine everything into a useful tool -- a simple grade tracker:
students = ["Maria", "Carlos", "Destiny", "Juan", "Aisha"]
grades = [88, 72, 95, 65, 81]
print("=== AI Foundations Grade Report ===\n")
for i in range(len(students)):
name = students[i]
grade = grades[i]
if grade >= 90:
letter = "A"
elif grade >= 80:
letter = "B"
elif grade >= 70:
letter = "C"
else:
letter = "Needs Support"
print(f" {name}: {grade} ({letter})")
average = sum(grades) / len(grades)
print(f"\n Class Average: {average:.1f}")
You just built a grade report system. The same logic powers real student information systems used in schools across San Antonio.
Try This
Create a "Community Resource Checker" in Google Colab. Make a list of 5 community resources (food bank, library, clinic, etc.) with their hours. Use a loop and if/else to check which ones are currently open (you can hardcode the current time for now). Print a formatted list of open resources.
Talk About It
Now that you can use lists and loops, what repetitive task in your life or work would you want to automate? How would you break it down into steps a computer could follow?