Loops
In Python, there are several loop constructs commonly used for solving array problems. Here are the most common ones:
-
For Loop: The
for
loop is widely used for iterating over elements in an array or any iterable object.It allows you to execute a block of code for each element in the array.
arr = [1, 2, 3, 4, 5] for num in array: print(num)
-
While Loop:
The
while
loop is used when you need to execute a block of code repeatedly as long as a condition is true.It's often used when you don't know in advance how many iterations are needed.
i = 0 while i < len(array): print(array[i]) i += 1
-
Nested Loops: Nested loops involve placing one loop inside another loop. They are used when you need to iterate over elements of a multi-dimensional array or perform operations that require multiple levels of iteration. For example:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for row in matrix: for num in row: print(num)
-
Enumerate: The
enumerate()
function is used to iterate over both the elements and their indices in an array. It returns tuples containing the index and the corresponding element. For example:for i, num in enumerate(arr): print(f"Element at index {i} is {num}")