Looping Through Arrays in Python: Iterating Over Array Elements

thumb_up 1  ·  sell Python array iteration, Looping through elements in Python arrays, Iterating over a Python array

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 L oop 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 I ndex

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.

 

 

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back