-1

Given an array called array, loop through all of its elements and print them out.

I have tried to use the following code but it is giving me the error TypeError: list indices must be integers, not str:

for element in array:
   print(array[element])

I have found the article Accessing the index in 'for' loops and I've tried to implement it like so:

for element, x in enumerate(array):
   print(array[element])

This still does not print what I was searching for.

  • Can you share some samples inputs? – Daniel Hao Jul 22 '23 at 13:20
  • @DanielHao Of course, for example I have even tried: `for element, x in enumerate(array): print(x)`. This seems to work, but I do not comprehend the need for "enumerate" and two variables ("element" and "x") when I will only be using one in the end. – Antonio De Angelis Jul 22 '23 at 13:22
  • Try to think of `index, elements` of enumerate.... Because enumerate gives a tuple of `index, element` – Daniel Hao Jul 22 '23 at 13:23
  • You're already looping over the elements. Use `print(element)`. If you want to loop over the indices, use `for element in range(len(array))` or `for index, element in enumerate(array)` to get both the indices and elements. – B Remmelzwaal Jul 22 '23 at 13:24

1 Answers1

3

Using normal for loop if you only need the elements of the array:

for element in array:
    print(element)

Using enumerate if you need the element and the index:

for index, element in enumerate(array):
    print(f"index {index} has element: {element}")
SDeVuyst
  • 138
  • 1
  • 8