CodesCompiler
πŸ”
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact πŸš€ Get Started Free

PYTHON - Loop Arrays

Python - Loop Arrays

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

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

Python for Loop with Array

Thefor loopis 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 βˆ’

PYTHON CODE
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 βˆ’

PYTHON CODE
56
42
23
85
45

Python while Loop with Array

Inwhile 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 βˆ’

PYTHON CODE
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 βˆ’

PYTHON CODE
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 aforloop.

Example

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

PYTHON CODE
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 βˆ’

PYTHON CODE
56.0
42.0
23.0
85.0
45.0