Python – Loop Arrays
In Python, a loop is a control structure that allows you to repeatedly execute a block of code. When working with arrays in Python, you can use loops to iterate over each element in the array and perform certain operations. This is particularly useful when you want to perform the same action on each item in an array.
For Loop
The for loop is commonly used to iterate over arrays in Python. It allows you to loop through each element in the array and perform a specific action. Here’s an example:
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
In this example, the for
loop iterates over each element in the fruits
array. The variable fruit
takes on the value of each element in the array, one by one. The print()
function is then used to display each fruit on a new line.
The output of this code will be:
apple
banana
orange
While Loop
Another way to loop through arrays in Python is by using a while loop. The while
loop continues iterating as long as a certain condition is true. Here’s an example:
fruits = ["apple", "banana", "orange"]
index = 0
while index < len(fruits):
print(fruits[index])
index += 1
In this example, we initialize a variable index
to 0. The while
loop continues as long as the value of index
is less than the length of the fruits
array. Inside the loop, we print the element at the current index and then increment the index by 1.
The output of this code will be the same as the previous example:
apple
banana
orange
Looping with Range
The range()
function is often used in conjunction with loops to generate a sequence of numbers. This can be useful when you want to loop a specific number of times, or when you need to access elements in an array by their index. Here’s an example:
fruits = ["apple", "banana", "orange"]
for i in range(len(fruits)):
print(fruits[i])
In this example, the range()
function generates a sequence of numbers from 0 to the length of the fruits
array minus 1. The for
loop then iterates over these numbers, and we use them as indices to access the elements in the fruits
array.
The output of this code will be the same as the previous examples:
apple
banana
orange
Conclusion
Looping through arrays in Python is a common task when working with data. The for
loop and while
loop are both useful for iterating over each element in an array. Additionally, the range()
function can be used to generate a sequence of numbers for looping purposes. By understanding and using these looping techniques, you can efficiently process arrays and perform operations on each element.