Last modified: Jun 10, 2023 By Alexander Williams

How to Create Array in Python Using For loop

To create an array in Python using a for loop, you can see this example:

# Define an empty list
my_array = []

# Use a for loop to iterate and append elements to the array
for i in range(5):
    my_array.append(i)

# Print the array
print(my_array)

Output:

[0, 1, 2, 3, 4]

However, in the above example we:

  1. Define an empty list that will serve as our array.
  2. Use a for loop to iterate over a range or any iterable.
  3. Inside the loop, append each element to the list.

You can modify the range or iterable to suit your specific requirements. Additionally, the elements appended to the array can be of any data type or object in Python.