Looping Through Arrays in Python: Using For and While Loops
Explore how to loop through arrays in Python using for
and while
loops. Learn how to iterate over array elements to perform various operations like accessing, modifying, and aggregating data with practical examples.
>
Python - Loop Arrays
Loops are used to repeatedly execute a block of code. In Python, there are two types of loops: for
loop and while
loop. Since arrays behave like sequences, you can iterate through their elements using loops. Looping through arrays allows you to perform operations such as accessing, modifying, searching, or aggregating elements.
Python for Loop with Array
The for
loop is used when the number of iterations is known. When used with an array, the loop continues until it has iterated over every element.
Syntax
import array as arr
newArray = arr.array('i', [56, 42, 23, 85, 45])
for iterate in newArray:
print(iterate)
Output
56
42
23
85
45
Python while Loop with Array
In a while
loop, the iteration continues as long as the specified condition is true. When using this loop with arrays, initialize a loop variable before entering the loop. This variable often represents an index for accessing elements. Inside the loop, manually update the loop variable.
Syntax
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 loop variable
idx += 1
Output
96
26
56
76
46
Python for Loop with Array Index
Use the built-in len()
function to find the length of an array. Create a range
object with the length to get the indices, then access the elements in a for
loop.
Syntax
import array as arr
a = arr.array('d', [56, 42, 23, 85, 45])
l = len(a)
for x in range(l):
print(a[x])
Output
56.0
42.0
23.0
85.0
45.0