Iterate through array list in Python 3.5

Hi people, if you read my previous article about Python 3.5 then you know that I am going to create a game with Python (maybe with Panda3D or PyGame) and distribute it on the gaming market place. However before we can create game we need to know some basic about python 3 and in this post I am going to continue with the basic python tutorial first. Today we are going to talk about how to iterate through an array list in Python 3.5.

There are two method we can use to iterate through a list in Python, we can either use the while loop or the for loop. First I am going to show you how to do it with the while loop.

 hello = ["Hello", "World", "!"]
 count = 0
 while(count < len(hello)):
     print(hello[count])
     count += 1

Use the while loop to iterate requires we to create an extra counter which is ‘count’ in this example.

Now lets take a look at the for loop.

 hello = ["Hello", "World", "!"]
 for item in hello:
     print(item)

The above for loop will produce the same outcome

Hello
World
!

but there is no counter involves in the for loop. Therefore I would have preferred to use the for loop instead of the while loop unless for some special reason not to use it.

If you are using NetBeans IDE 8.1 then the complete code for this program is as follow:

if __name__ == "__main__":
    hello = ["Hello", "World", "!"]
    for item in hello:
        print(item)

Also notice that the python’s build in function print method will print each item in the list in a new line, if you want to print it in one single line then you can use below program instead.

if __name__ == "__main__":
    hello = ["Hello", "World", "!"]
    hello_string = ""
    for item in hello:
        hello_string += item + " "
    print(hello_string)

I hope you do enjoy with this tutorial and wish you good luck in your Python 3 learning! This blog will be updated at least once per day so if you are into game design do come back and read the next article.