The Python list object is very useful to the coder, especially when they have to store data and keep track of it in their projects. Not only can the coder make use of the list object to store data in it, but they can also make use of the data by using different utilities which the Python computer programming language offers by default.
Through this article, you are going to learn how to print the elements of a Python list object by making use of a for loop. For those of you who don’t know, the for loop Python utility can be used to interact with any kind of object which is iterable.
And since the Python list object is an iterable one, we can make use of the for loop statement to access its elements. This time, we are going to make use of the Python for loop utility only to print each element of the Python list object.
What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.
Before going any further with this tutorial, make sure to launch a new Python interactive shell so you can practice the code by yourself. Only by practicing the examples by yourself, you can get better with the Python computer programming language, or any other computer language.
Once you have managed to open a new Python interactive console, make use of the following statement to create a new list object. Feel free to add the elements you like. Personally I am using some string objects to populate my Python list object.
l = [‘apple’, ‘banana’, ‘cherry’]
Now to print each one of the elements stored in the above list object, we can make use of the for loop utility like shown below.
for fruit in l:print(fruit)
Once the piece of the Python code shown above is being run on my interactive shell, I get the following output.
apple
banana
cherry
As you can see from the above output, we managed to print each one of the elements of the list object by making use of the Python for loop utility.
Final thoughts
One can make use of the Python for loop utility to access the elements of any iterable object. Try by yourself with a string object.