Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - Loop Arrays



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

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

Python for Loop with Array

Thefor 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 arrnewArray = arr.array('i', [56, 42, 23, 85, 45])for iterate in newArray:   print (iterate)

The above code will produce the following result −

5642238545

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 −

import array as arr# creating arraya = arr.array('i', [96, 26, 56, 76, 46])# checking the lengthl = len(a)# loop variableidx = 0# while loopwhile idx < l:   print (a[idx])   # incrementing the while loop   idx+=1

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

9626567646

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 afor loop.

Example

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

import array as arra = 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.042.023.085.045.0
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp