Story – Python Arrays

As Alex continued to explore Python programming, they became interested in working with arrays. They had learned about Python’s built-in list data type, but they wanted to learn more about arrays and how they could be used in programming.

Alex began by reading about arrays in Python and learning how they were different from lists. They discovered that arrays were similar to lists in that they could hold multiple values, but that arrays were typically used for more specialized purposes such as numerical computations.

To better understand arrays, Alex decided to create a simple program that would use arrays to store and manipulate a list of numbers. They began by creating a simple list of numbers:

# Creating a list of numbers
# Author: Alex
# Date: 2/25/2023

numbers = [1, 2, 3, 4, 5]

In this code, Alex created a simple list of numbers using square brackets to enclose the values.

Next, Alex wanted to convert the list into an array. They learned that Python’s array module provided a way to create arrays of different data types, including integers, floating point numbers, and more. They began by importing the array module:

# Importing the array module
# Author: Alex
# Date: 2/25/2023

import array

In this code, Alex imported the array module to use its functionality.

Next, Alex used the array module to create an array from the list of numbers:

# Creating an array from a list of numbers
# Author: Alex
# Date: 2/25/2023

numbers_array = array.array('i', numbers)

In this code, Alex created an array called numbers_array by calling the array constructor from the array module. They passed in two parameters to the constructor: the data type of the array (‘i’ for integer), and the list of values that they wanted to store in the array.

Now that Alex had created an array, they could use its built-in methods to manipulate the data. For example, they could append a new number to the end of the array using the append() method:

# Appending a number to an array
# Author: Alex
# Date: 2/25/2023

numbers_array.append(6)

In this code, Alex called the append() method on the numbers_array array and passed in a new value of 6 to add it to the end of the array.

Finally, Alex wanted to print out the values in the array to make sure that everything was working correctly:

# Printing the values in an array
# Author: Alex
# Date: 2/25/2023

for number in numbers_array:
    print(number)

In this code, Alex used a for loop to iterate over the values in the numbers_array array and print them out to the console.

Alex was excited to see how easy it was to work with arrays in Python, and they realized that arrays could be used to perform many different types of computations and manipulations. They looked forward to exploring more advanced applications of arrays in Python programming.