Python - Array Exercises

Hello there, aspiring programmers! I'm thrilled to be your guide on this exciting journey into the world of Python arrays. As a computer science teacher with years of experience, I've seen countless students light up with understanding when they grasp these concepts. So, let's dive in and make arrays fun and easy to understand!

Python - Array Exercises

What is an Array?

Before we jump into our examples, let's start with the basics. In Python, we don't have built-in array data structures like in some other languages. Instead, we use lists, which are incredibly versatile and powerful. For our purposes today, we'll use lists as our "arrays."

An array (or list in Python) is like a container that can hold multiple items. Imagine a train with several carriages, each carrying a piece of data. That's essentially what an array is in programming!

Example 1: Creating and Accessing Arrays

Let's start with a simple example:

fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0])  # Output: apple
print(fruits[2])  # Output: cherry

In this example, we've created an array (list) called fruits. Each item in the array has an index, starting from 0. So, fruits[0] gives us the first item, "apple", and fruits[2] gives us the third item, "cherry".

Think of it like a row of lockers in a school. If you're standing at the start of the row (index 0), the third locker would be two steps away (index 2).

Example 2: Modifying Arrays

Arrays are mutable, which means we can change them after they're created. Let's see how:

numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers)  # Output: [1, 2, 10, 4, 5]

numbers.append(6)
print(numbers)  # Output: [1, 2, 10, 4, 5, 6]

numbers.remove(2)
print(numbers)  # Output: [1, 10, 4, 5, 6]

Here, we've done three operations:

  1. We changed the value at index 2 from 3 to 10.
  2. We added a new number (6) to the end of the array using append().
  3. We removed the number 2 from the array using remove().

It's like editing a playlist. You can change a song (modify), add a new song at the end (append), or remove a song you don't like anymore (remove).

Example 3: Looping Through Arrays

One of the most powerful features of arrays is the ability to process all items quickly. We do this using loops:

colors = ["red", "green", "blue", "yellow"]

# Using a for loop
for color in colors:
    print(f"I love {color}!")

# Using a while loop
i = 0
while i < len(colors):
    print(f"Color at index {i} is {colors[i]}")
    i += 1

In the first loop, we're saying "I love" each color. It's like going through your wardrobe and complimenting each piece of clothing.

The second loop uses a different approach. We're manually increasing our index (i) and stopping when we reach the end of the array. This is like counting your steps as you walk past each item in a museum.

Exercise Programs

Now that we've covered the basics, let's try some exercises to reinforce what we've learned. Remember, practice makes perfect!

Exercise 1: Sum of Array Elements

Write a program that calculates the sum of all elements in an array of numbers.

def sum_array(arr):
    total = 0
    for num in arr:
        total += num
    return total

numbers = [1, 2, 3, 4, 5]
print(f"The sum is: {sum_array(numbers)}")  # Output: The sum is: 15

This function goes through each number in the array and adds it to a running total. It's like counting all the coins in your piggy bank!

Exercise 2: Find the Largest Element

Create a function that finds the largest element in an array.

def find_largest(arr):
    if len(arr) == 0:
        return None
    largest = arr[0]
    for num in arr:
        if num > largest:
            largest = num
    return largest

numbers = [3, 7, 2, 8, 1, 9, 5, 4]
print(f"The largest number is: {find_largest(numbers)}")  # Output: The largest number is: 9

This function starts by assuming the first number is the largest, then compares each number to the current largest. It's like a championship where each number competes to be the champion!

Exercise 3: Reverse an Array

Write a function that reverses the order of elements in an array.

def reverse_array(arr):
    return arr[::-1]

original = [1, 2, 3, 4, 5]
reversed_arr = reverse_array(original)
print(f"Original array: {original}")
print(f"Reversed array: {reversed_arr}")

This uses a Python slice with a step of -1 to reverse the array. It's like flipping through a photo album from back to front!

Here's a table summarizing the array methods we've used:

Method Description Example
append() Adds an element to the end of the list fruits.append("grape")
remove() Removes the first occurrence of the specified element fruits.remove("banana")
len() Returns the number of elements in the list len(fruits)
Indexing Accesses or modifies an element at a specific position fruits[0] or fruits[1] = "kiwi"
Slicing Returns a portion of the list fruits[1:3] or fruits[::-1] for reversal

Remember, arrays (lists in Python) are fundamental to programming and are used in countless applications. They're like the Swiss Army knives of data structures - versatile, useful, and essential to have in your coding toolkit.

As you practice these exercises, you'll find yourself becoming more comfortable with arrays. Don't be discouraged if it doesn't click immediately - learning to code is a journey, and every step forward is progress. Keep experimenting, keep asking questions, and most importantly, keep coding!

Happy coding, future programmers! May your arrays always be sorted and your loops infinite only when you want them to be!

Credits: Image by storyset