How To Create an Array In Python Using the For Loop

In this tutorial, we will learn how to create an array in Python using a for loop. Arrays are versatile data structures that can store multiple values in a single variable. In Python, we can create and manipulate arrays using the built-in list or the numpy library. We will be focusing on lists for this tutorial.

Learning how to create an array through a for loop will provide you with the skills to manage and manipulate data efficiently. Let’s dive into the steps to create an array using a for loop in Python.

Step 1: Initialize an empty list

First, we will create an empty list that will act as our array. You can initialize a list using the square brackets [].

Step 2: Construct a for loop

Now, we will construct a for loop to iterate through a specified range of numbers. In this tutorial, we will use the range() function to create a range of numbers to iterate through.

Here, the range() function takes two arguments: a start value and an end value. You can also provide a third argument as a step value, but in our case, the default value of 1 is fine.

Step 3: Append values to the list

Within the for loop, we will append a value to our list, effectively creating an array. The append() function allows us to add a value to the list at the end of its current state.

Here is an example of adding numbers from the range 1 to 5:

The output will be:

[1, 2, 3, 4, 5]

Step 4: Modify the values before appending

You can modify the values before appending them to the list. This allows you to store manipulated values in the array.

For instance, you can store the square of each value in the range:

The output will be:

[1, 4, 9, 16, 25]

There you have it! The above example showcases how to create an array in Python using a for loop.


Creating an array in Python using a for loop is a simple and efficient way to store and manipulate data. Moreover, you can customize the looping process and modify the elements before appending them to the list. Understanding how to use for loops to create arrays will greatly enhance your skills in maintaining and processing data in Python.