Python - Loop Arrays



Loops are used to repeatedly execute a block of code. In Python, there are two types of loops named for loop and while loop. Since the array object behaves like a sequence, you can iterate through its elements with the help of loops.

The reason for looping through arrays is to perform operations such as accessing, modifying, searching, or aggregating elements of the array.

Python for Loop with Array

The for loop is used when the number of iterations is known. If we use it with an iterable like array, the iteration continues until it has iterated over every element in the array.

Example

The below example demonstrates how to iterate over an array using the "for" loop −

import array as arr
newArray = arr.array('i', [56, 42, 23, 85, 45])
for iterate in newArray:
   print (iterate)

The above code will produce the following result −

56
42
23
85
45

Python while Loop with Array

In while loop, the iteration continues as long as the specified condition is true. When you are using this loop with arrays, initialize a loop variable before entering the loop. This variable often represents an index for accessing elements in the array. Inside the while loop, iterate over the array elements and manually update the loop variable.

Example

The following example shows how you can loop through an array using a while loop −

import array as arr

# creating array
a = arr.array('i', [96, 26, 56, 76, 46])

# checking the length
l = len(a)

# loop variable
idx = 0

# while loop
while idx < l:
   print (a[idx])
   # incrementing the while loop
   idx+=1

On executing the above code, it will display the following output −

96
26
56
76
46

Python for Loop with Array Index

We can find the length of array with built-in len() function. Use it to create a range object to get the series of indices and then access the array elements in a for loop.

Example

The code below illustrates how to use for loop with array index.

import array as arr
a = arr.array('d', [56, 42, 23, 85, 45])
l = len(a)
for x in range(l):
   print (a[x])

On running the above code, it will show the below output −

56.0
42.0
23.0
85.0
45.0
Advertisements