Introduction to Python Programming

Andrew J. Pounds, Ph.D.

📦 Exercise Eight: Arrays (Lists) in Python

So far, we've worked with individual variables that each hold a single value. But what if you need to store a collection of related values—like a list of test scores, a series of temperatures, or the names of students in a class? Creating separate variables for each one would be tedious and impractical. This is where arrays (called lists in Python) come in!

What You'll Learn:
  • What arrays (lists) are and why they're useful
  • How to create and access elements in a list
  • How to modify list elements
  • How to use loops to process all elements in a list
  • Common list operations and methods
🏠 Real-World Analogy:

Think of a list like a row of mailboxes in an apartment building. Each mailbox has a number (its index), and each mailbox can hold one piece of mail (a value). Instead of saying "the mail in John's box, the mail in Mary's box, the mail in Bob's box..." you can just say "the mail in box 0, box 1, box 2..." This makes it much easier to work with large collections of data!

📋 1. What is a List?

A list is an ordered collection of values stored under a single variable name. Each value in the list is called an element, and each element has a numbered position called an index.

📝 Terminology Note:

In many programming languages, this data structure is called an array. Python calls it a list, but the concept is the same. We'll use both terms interchangeably in this exercise.

Creating a List

To create a list, use square brackets [] with values separated by commas:

# A list of integers
scores = [85, 92, 78, 90, 88]

# A list of strings
names = ["Alice", "Bob", "Charlie", "Diana"]

# A list of floating-point numbers
temperatures = [72.5, 68.3, 75.0, 71.2, 69.8]

# An empty list
empty_list = []

Visualizing a List

Here's how the scores list looks in memory:

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

85
92
78
90
88
index 0
index 1
index 2
index 3
index 4
⚠️ Critical: Indexing Starts at 0!

In Python (and most programming languages), the first element is at index 0, not index 1. This is called zero-based indexing. So a list with 5 elements has indices 0, 1, 2, 3, and 4.

🎯 2. Accessing List Elements

To access an individual element, use the list name followed by the index in square brackets:

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

# Access individual elements
print(scores[0])  # First element
print(scores[1])  # Second element
print(scores[4])  # Fifth (last) element
85
92
88

Using Variables as Indices

You can use a variable to specify which index to access:

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

i = 2
print("The element at index", i, "is", scores[i])
The element at index 2 is 78

Negative Indexing

Python also supports negative indices, which count from the end of the list:

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

print(scores[-1])  # Last element
print(scores[-2])  # Second to last
print(scores[-5])  # First element (same as scores[0])
88
90
85

Negative Indexing Visualization

85
92
78
90
88
-5
-4
-3
-2
-1

The len() Function

Use len() to find out how many elements are in a list:

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

print("Number of scores:", len(scores))
Number of scores: 5
💡 Pro Tip:

The last valid index is always len(list) - 1. For a list with 5 elements, the last index is 4, not 5!

✏️ 3. Modifying List Elements

Lists are mutable, meaning you can change their elements after creation:

scores = [85, 92, 78, 90, 88]
print("Before:", scores)

# Change the third element (index 2)
scores[2] = 95
print("After:", scores)
Before: [85, 92, 78, 90, 88]
After: [85, 92, 95, 90, 88]

Adding Elements to a List

Method Description Example
append(x) Add element x to the end scores.append(100)
insert(i, x) Insert element x at index i scores.insert(0, 100)
scores = [85, 92, 78]
print("Original:", scores)

# Add to the end
scores.append(90)
print("After append:", scores)

# Insert at a specific position
scores.insert(1, 100)  # Insert 100 at index 1
print("After insert:", scores)
Original: [85, 92, 78]
After append: [85, 92, 78, 90]
After insert: [85, 100, 92, 78, 90]

Removing Elements from a List

Method Description Example
remove(x) Remove first occurrence of x scores.remove(78)
pop() Remove and return last element last = scores.pop()
pop(i) Remove and return element at index i second = scores.pop(1)
scores = [85, 92, 78, 90, 88]
print("Original:", scores)

# Remove by value
scores.remove(78)
print("After remove(78):", scores)

# Remove last element
last = scores.pop()
print("Popped value:", last)
print("After pop():", scores)
Original: [85, 92, 78, 90, 88]
After remove(78): [85, 92, 90, 88]
Popped value: 88
After pop(): [85, 92, 90]

🔄 4. Using Loops with Lists

This is where the real power of lists becomes apparent! Loops allow you to process every element in a list with just a few lines of code. Without loops, you'd have to write separate code for each element—imagine doing that for a list with 1000 items!

✅ Why Loops + Lists are Powerful:
  • Process any number of elements with the same code
  • No need to know the list size in advance
  • Easy to perform calculations on all elements
  • Code is shorter, cleaner, and easier to maintain

Method 1: Using for with range()

Use the index to access each element:

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

# Print each score with its index
for i in range(len(scores)):
    print("Score", i, ":", scores[i])
Score 0 : 85
Score 1 : 92
Score 2 : 78
Score 3 : 90
Score 4 : 88

How Does This Work?

  1. len(scores) returns 5 (the number of elements)
  2. range(5) generates: 0, 1, 2, 3, 4
  3. The loop runs 5 times, with i taking each value
  4. scores[i] accesses the element at index i

Method 2: Direct Iteration with for

Python allows you to iterate directly over the elements (simpler when you don't need the index):

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

# Print each score directly
for score in scores:
    print("Score:", score)
Score: 85
Score: 92
Score: 78
Score: 90
Score: 88
💡 Which Method Should You Use?
  • Use for i in range(len(list)) when you need the index (to modify elements, compare adjacent elements, or show position)
  • Use for item in list when you just need the values (simpler and more readable)

Method 3: Using while Loop

You can also use a while loop with an index variable:

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

i = 0
while i < len(scores):
    print("Score at index", i, ":", scores[i])
    i += 1
Score at index 0 : 85
Score at index 1 : 92
Score at index 2 : 78
Score at index 3 : 90
Score at index 4 : 88

🧮 5. Common List Operations with Loops

Calculating the Sum

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

total = 0
for score in scores:
    total += score

print("Sum of all scores:", total)
Sum of all scores: 433

Calculating the Average

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

total = 0
for score in scores:
    total += score

average = total / len(scores)
print("Average score:", average)
Average score: 86.6

Finding the Maximum Value

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

maximum = scores[0]  # Start with the first element

for score in scores:
    if score > maximum:
        maximum = score

print("Highest score:", maximum)
Highest score: 92

Finding the Minimum Value

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

minimum = scores[0]  # Start with the first element

for score in scores:
    if score < minimum:
        minimum = score

print("Lowest score:", minimum)
Lowest score: 78

Counting Elements that Meet a Condition

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

# Count how many scores are 90 or above
count = 0
for score in scores:
    if score >= 90:
        count += 1

print("Number of A grades (90+):", count)
Number of A grades (90+): 2

Modifying All Elements

When you need to modify elements, use indexing:

# Add 5 bonus points to every score
scores = [85, 92, 78, 90, 88]
print("Before bonus:", scores)

for i in range(len(scores)):
    scores[i] = scores[i] + 5

print("After bonus:", scores)
Before bonus: [85, 92, 78, 90, 88]
After bonus: [90, 97, 83, 95, 93]
⚠️ Important: If you try to modify elements using for score in scores, the original list won't change! You must use indexing to modify the actual list elements.

🔍 6. Searching in Lists

Linear Search: Finding a Value

def find_value(my_list, target):
    """Search for target in my_list and return its index, or -1 if not found"""
    for i in range(len(my_list)):
        if my_list[i] == target:
            return i  # Found it!
    return -1  # Not found

# Test the search function
scores = [85, 92, 78, 90, 88]

result = find_value(scores, 90)
if result != -1:
    print("Found 90 at index", result)
else:
    print("90 not found")

result = find_value(scores, 100)
if result != -1:
    print("Found 100 at index", result)
else:
    print("100 not found")
Found 90 at index 3
100 not found

Checking if a Value Exists

Python has a built-in way to check if a value is in a list:

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

if 92 in scores:
    print("92 is in the list")

if 100 not in scores:
    print("100 is not in the list")
92 is in the list
100 is not in the list

🏗️ 7. Building Lists with Loops

You can use loops to create lists dynamically:

Creating a List of Squares

# Create a list of squares from 1 to 10
squares = []

for i in range(1, 11):
    squares.append(i ** 2)

print("Squares:", squares)
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Reading Values from User Input

# Get 5 scores from the user
scores = []

print("Enter 5 test scores:")
for i in range(5):
    score = int(input("Score " + str(i + 1) + ": "))
    scores.append(score)

print("You entered:", scores)
Enter 5 test scores:
Score 1: 85
Score 2: 92
Score 3: 78
Score 4: 90
Score 5: 88
You entered: [85, 92, 78, 90, 88]

Creating a List Until a Sentinel Value

# Keep reading numbers until user enters -1
numbers = []

print("Enter numbers (-1 to stop):")

while True:
    num = int(input("Enter a number: "))
    if num == -1:
        break
    numbers.append(num)

print("You entered", len(numbers), "numbers:", numbers)
Enter numbers (-1 to stop):
Enter a number: 10
Enter a number: 20
Enter a number: 30
Enter a number: -1
You entered 3 numbers: [10, 20, 30]

🎯 8. Complete Examples

Example 1: Grade Statistics Calculator

# Grade Statistics Calculator
print("=== Grade Statistics Calculator ===")
print()

# Get number of students
num_students = int(input("How many students? "))

# Collect grades
grades = []
for i in range(num_students):
    grade = float(input("Enter grade for student " + str(i + 1) + ": "))
    grades.append(grade)

# Calculate statistics
total = 0
highest = grades[0]
lowest = grades[0]

for grade in grades:
    total += grade
    if grade > highest:
        highest = grade
    if grade < lowest:
        lowest = grade

average = total / len(grades)

# Display results
print()
print("=== Results ===")
print("Number of students:", len(grades))
print("Highest grade:", highest)
print("Lowest grade:", lowest)
print("Average grade:", round(average, 2))
=== Grade Statistics Calculator ===

How many students? 5
Enter grade for student 1: 85
Enter grade for student 2: 92
Enter grade for student 3: 78
Enter grade for student 4: 90
Enter grade for student 5: 88

=== Results ===
Number of students: 5
Highest grade: 92.0
Lowest grade: 78.0
Average grade: 86.6

Example 2: Temperature Tracker

# Weekly Temperature Tracker
print("=== Weekly Temperature Tracker ===")
print()

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
temperatures = []

# Collect temperatures
for day in days:
    temp = float(input("Enter temperature for " + day + ": "))
    temperatures.append(temp)

# Find hottest and coldest days
hottest_index = 0
coldest_index = 0

for i in range(len(temperatures)):
    if temperatures[i] > temperatures[hottest_index]:
        hottest_index = i
    if temperatures[i] < temperatures[coldest_index]:
        coldest_index = i

# Calculate average
total = 0
for temp in temperatures:
    total += temp
average = total / len(temperatures)

# Display results
print()
print("=== Weekly Summary ===")
print("Hottest day:", days[hottest_index], "at", temperatures[hottest_index], "degrees")
print("Coldest day:", days[coldest_index], "at", temperatures[coldest_index], "degrees")
print("Average temperature:", round(average, 1), "degrees")
=== Weekly Temperature Tracker ===

Enter temperature for Monday: 72
Enter temperature for Tuesday: 75
Enter temperature for Wednesday: 80
Enter temperature for Thursday: 78
Enter temperature for Friday: 71
Enter temperature for Saturday: 68
Enter temperature for Sunday: 73

=== Weekly Summary ===
Hottest day: Wednesday at 80.0 degrees
Coldest day: Saturday at 68.0 degrees
Average temperature: 73.9 degrees

Example 3: Quiz Score Analyzer

# Quiz Score Analyzer
print("=== Quiz Score Analyzer ===")
print()

scores = [85, 92, 78, 95, 88, 72, 90, 83, 97, 80]

print("Scores:", scores)
print()

# Count grades by category
a_count = 0  # 90-100
b_count = 0  # 80-89
c_count = 0  # 70-79
d_count = 0  # 60-69
f_count = 0  # Below 60

for score in scores:
    if score >= 90:
        a_count += 1
    elif score >= 80:
        b_count += 1
    elif score >= 70:
        c_count += 1
    elif score >= 60:
        d_count += 1
    else:
        f_count += 1

# Display grade distribution
print("Grade Distribution:")
print("A (90-100):", a_count, "students")
print("B (80-89):", b_count, "students")
print("C (70-79):", c_count, "students")
print("D (60-69):", d_count, "students")
print("F (below 60):", f_count, "students")
=== Quiz Score Analyzer ===

Scores: [85, 92, 78, 95, 88, 72, 90, 83, 97, 80]

Grade Distribution:
A (90-100): 4 students
B (80-89): 4 students
C (70-79): 2 students
D (60-69): 0 students
F (below 60): 0 students

🛠️ 9. Built-in List Functions

Python provides several built-in functions that work with lists:

Function Description Example Result
len(list) Number of elements len([1, 2, 3]) 3
sum(list) Sum of all elements sum([1, 2, 3]) 6
min(list) Smallest element min([1, 2, 3]) 1
max(list) Largest element max([1, 2, 3]) 3
sorted(list) Returns a new sorted list sorted([3, 1, 2]) [1, 2, 3]
scores = [85, 92, 78, 90, 88]

print("Scores:", scores)
print("Count:", len(scores))
print("Sum:", sum(scores))
print("Min:", min(scores))
print("Max:", max(scores))
print("Sorted:", sorted(scores))
print("Average:", sum(scores) / len(scores))
Scores: [85, 92, 78, 90, 88]
Count: 5
Sum: 433
Min: 78
Max: 92
Sorted: [78, 85, 88, 90, 92]
Average: 86.6
💡 Pro Tip:

While these built-in functions are convenient, understanding how to implement them yourself using loops is crucial for learning programming. In an exam or interview, you might be asked to write your own version!

⚠️ Common Mistakes (And How to Fix Them)

Mistake 1: Index Out of Range

❌ Wrong:
scores = [85, 92, 78, 90, 88]
print(scores[5])  # ERROR! Index 5 doesn't exist
✅ Correct:
scores = [85, 92, 78, 90, 88]
print(scores[4])  # Last valid index is 4 (length - 1)

Mistake 2: Forgetting Zero-Based Indexing

❌ Wrong:
scores = [85, 92, 78]
print("First score:", scores[1])  # This is actually the SECOND element!
✅ Correct:
scores = [85, 92, 78]
print("First score:", scores[0])  # Index 0 is the first element

Mistake 3: Modifying List While Iterating Directly

❌ Wrong (doesn't modify the original list):
scores = [85, 92, 78]
for score in scores:
    score = score + 5  # This doesn't change the list!
print(scores)  # Still [85, 92, 78]
✅ Correct (use indexing to modify):
scores = [85, 92, 78]
for i in range(len(scores)):
    scores[i] = scores[i] + 5
print(scores)  # Now [90, 97, 83]

Mistake 4: Off-by-One Error in Loops

❌ Wrong:
scores = [85, 92, 78, 90, 88]
for i in range(1, len(scores)):  # Skips index 0!
    print(scores[i])
✅ Correct:
scores = [85, 92, 78, 90, 88]
for i in range(len(scores)):  # Starts at 0
    print(scores[i])

Mistake 5: Using Wrong Loop Limit

❌ Wrong:
scores = [85, 92, 78, 90, 88]
for i in range(len(scores) + 1):  # Goes one too far!
    print(scores[i])  # ERROR on last iteration
✅ Correct:
scores = [85, 92, 78, 90, 88]
for i in range(len(scores)):  # Correct limit
    print(scores[i])

✏️ Practice Exercises

Try writing these programs on your own!

Exercise 1: Sum and Average

Write a program that:

  1. Creates a list of 10 numbers (you can hardcode them or get input)
  2. Uses a loop to calculate the sum
  3. Calculates and displays the average

Challenge: Do NOT use the built-in sum() function—write your own loop!

Exercise 2: Find Maximum and Minimum

Write a program that:

  1. Creates a list of numbers
  2. Uses a loop to find the largest number
  3. Uses a loop to find the smallest number
  4. Displays both values

Challenge: Do NOT use the built-in min() or max() functions!

Exercise 3: Count Occurrences

Write a program that:

  1. Has a list of numbers (some may be repeated)
  2. Asks the user for a number to search for
  3. Counts how many times that number appears in the list
  4. Displays the count

Exercise 4: Reverse a List

Write a program that:

  1. Creates a list of numbers
  2. Creates a new list that contains the elements in reverse order
  3. Displays both the original and reversed lists

Hint: You can use negative indices or iterate backwards!

Exercise 5: Above and Below Average

Write a program that:

  1. Has a list of test scores
  2. Calculates the average
  3. Displays which scores are above average and which are below
  4. Counts how many are above and how many are below

Exercise 6: Running Total

Write a program that:

  1. Has a list of numbers: [5, 10, 15, 20, 25]
  2. Creates a new list where each element is the running total up to that point
  3. Result should be: [5, 15, 30, 50, 75]

Explanation: 5, 5+10=15, 5+10+15=30, etc.

📖 Quick Reference

Creating and Accessing Lists

Create a list:
my_list = [1, 2, 3, 4, 5]
Access element:
my_list[0]  # First element
my_list[-1] # Last element
Modify element:
my_list[2] = 99
Get length:
len(my_list)

Looping Through Lists

With index:
for i in range(len(my_list)):
    print(my_list[i])
Direct iteration:
for item in my_list:
    print(item)

Common List Methods

Add to end:
my_list.append(6)
Insert at position:
my_list.insert(0, 99)
Remove by value:
my_list.remove(3)
Remove by index:
my_list.pop(2)

⭐ Key Takeaways

  • ✓ Lists (arrays) store multiple values under a single variable name
  • ✓ List indices start at 0, not 1 (zero-based indexing)
  • ✓ The last valid index is len(list) - 1
  • ✓ Use square brackets to access elements: list[index]
  • ✓ Negative indices count from the end: list[-1] is the last element
  • ✓ Loops are essential for processing all elements in a list
  • ✓ Use for i in range(len(list)) when you need the index
  • ✓ Use for item in list when you just need the values
  • ✓ To modify list elements, you must use indexing
  • ✓ Built-in functions like len(), sum(), min(), max() work with lists

❓ Need Help?

If your program doesn't work, check these common issues:

  1. IndexError: list index out of range—Are you trying to access an index that doesn't exist? Remember, a list of length 5 has indices 0-4, not 1-5!
  2. List not changing—Are you using indexing to modify elements? for item in list doesn't let you modify the original list.
  3. Off-by-one error—Double-check your loop bounds. range(len(list)) is usually what you want.
  4. Empty list errors—Before accessing list[0] or using list[0] as an initial value, make sure the list isn't empty!
💡 Debugging Tip: Print your list and indices to see what's happening:
scores = [85, 92, 78]
print("List:", scores)
print("Length:", len(scores))

for i in range(len(scores)):
    print("Index", i, "->", scores[i])
Remember: Lists combined with loops are incredibly powerful! They let you process any amount of data with just a few lines of code. Master these concepts, and you'll be able to handle real-world data processing tasks like analyzing survey results, processing student grades, or working with scientific measurements. Practice building, accessing, and modifying lists until it becomes second nature!