4 Ways to Iterate Arrays in Python
In Python, there are various methods to iterate through an array, such as:
- “Using a for loop:”
arr = [1, 2, 3, 4, 5]
for element in arr:
print(element)
- Utilizing a while loop and an index:
arr = [1, 2, 3, 4, 5]
index = 0
while index < len(arr):
print(arr[index])
index += 1
- Utilize the enumerate() function:
arr = [1, 2, 3, 4, 5]
for index, element in enumerate(arr):
print(f"Index {index}: {element}")
- Utilize the zip() function (used for iterating over multiple arrays simultaneously):
arr1 = [1, 2, 3]
arr2 = ['a', 'b', 'c']
for element1, element2 in zip(arr1, arr2):
print(f"{element1} - {element2}")
- Utilizing list comprehension:
arr = [1, 2, 3, 4, 5]
[print(element) for element in arr]
These methods allow for choosing the appropriate way to traverse an array based on specific needs.