Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Going through arrays with for loops in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

This still does not print what I was searching for.

>Solution :

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}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading