Loops and Array in Python
Keywords: array, loops, list, variable
By using loops in Python we can iterate all the elements of an Array, and therefore manage the values in each of the elements
How to access all elements of an array in Python?
Okay, now you have created your Array in Python and want to start using it. But how do we access the elements in the Array in a easy way? It’s actually really simple, we just use a loop. For example, maybe you want to go through all the values in the array to find a particular value. You can iterate through all the values in an array using a loop. If you need to have a look at how the loop in Python is created and used, have a look at this page.
In Python, it is possible to iterate, go through all elements of an array using a loop
Example: Process all elements of an array in Python
Let’s take a example on how to create a loop that process the elements of an array in Python. We will use our favorite array – the one that contains animals.
Start by creating the Array (remember how we did that?)
animal_arr = ["Dog", "Shark", "Cat", "Horse", "Snake"]
Illustrated as
Okay, now that we have our array, we want to use a loop to print all the values in animal_arr
for animals in animals_arr:
print(animals)
The results is:
Dog
Shark
Cat
Horse
Snake
You can also select each index individually and get exactly the same result:
for i in range(len(animal_arr)):
print(animal_arr[i])
The result in this case is exactly the same as the previous one
Dog
Shark
Cat
Horse
Snake