✏️ Explanatory Question

Traversal in Array using Python

👁 220 Views
📘 Detailed Answer
No previous question
No next question
💡

Answer with Explanation

In Python, you can traverse an array using a for loop. Here's an example:


arr = [1, 2, 3, 4, 5]

for element in arr:
    print(element)

This will print each element of the array arr on a new line.

You can also use a for loop with the range function to access each element by its index:


arr = [1, 2, 3, 4, 5]

for i in range(len(arr)):
    print(arr[i])

This will produce the same output as the previous example.

You can also use while loop for traversing the array:


arr = [1, 2, 3, 4, 5]

i = 0
while i < len(arr):
    print(arr[i])
    i += 1

This will also produce the same output as the previous examples.

No previous question
No next question