Python - Loop Arrays



Since the array object behaves like a sequence, you can iterate through its elements with the help of for loop or while loop.

"for" Loop with Array

Take a look at the following example −

import array as arr
a = arr.array('d', [1, 2, 3])
for x in a:
   print (x)

It will produce the following output

1.0
2.0
3.0

"while" Loop with Array

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

import array as arr
a = arr.array('d', [1, 2, 3])
l = len(a)
idx =0
while idx<l:
   print (a[idx])
   idx+=1

"for" Loop with Array Index

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

import array as arr
a = arr.array('d', [1, 2, 3])
l = len(a)
for x in range(l):
   print (a[x])

You will get the same output as in the first example.

Advertisements