“Python Lists Manipulation: With For Loops” continues our previous post, “Python Lists for absolute beginners“. This post is a more in-depth tutorial on python list data type.
You will learn how to make lists, work with individual elements, and loop through an entire list with a few lines of code regardless of how long the list is. Looping allows you to repeat a step, or set of steps, with items on a list. As a result, you’ll be able to work with lists of any size, including those with thousands or even millions of items.
How to Loop Through Python Lists
You often want to iterate through all elements in a given list while executing identical operations with every item. For instance, you could perform the same statistical operation on every element in a list of numbers. You can display individual topics from a list of posts on a blog. You can use Python’s for loop to perform the same task with every item in a list. Say we have a list of movie stars’ names and want to print every name. We could achieve this by getting the name from the list individually, but this technique will cause several issues. For one, it will be duplicative to accomplish this with a long list of names. Again, we’d have to modify our code every time the list changes. A for loop controls both problems by allowing Python to handle these problems internally.
Let us print out each name in a list of movie stars using for loops:
stars = ['Tom Cruise', 'Tom Hanks', 'Samuel L. Jackson', 'Harrison Ford', 'Robert Downey Jr.']
for star in stars :
print(star)
Line 1 defines the list, At line 2, we define the for loop. This line pulls a name from the list of stars and holds it in the variable star. In line 3, we print the name in the star variable. Python then repeats lines 2 and 3, once for every name in the stars list. You will understand it better if you read the code this way: “For every star in the stars list, print the star’s name.” The output is a simple printout of each name in the list:
Output:
Tom Cruise
Tom Hanks
Samuel L. Jackson
Harrison Ford
Robert Downey Jr.
How For Loops Works with Python Lists
The idea of looping is vital because it’s one of the most typical methods a computer automates repetitive tasks. We have for and while loops. For instance, in an uncomplicated loop, as we used the stars list, Python initially reads the first line of the loop:
for star in stars :
This line instructs Python to get the first item from the stars list and keep it in the variable star, “Tom Cruise”. Python then implements the following line:
print(star)
Python prints the current content of the star variable, “Tom Cruise”. Since the list still contains more items, Python goes back to the first line of the loop:
for star in stars :
Now Python will get the next name on the list, “Tom Hanks”, and keeps it star variable again. Python then implements the following line:
print(star)
Python will print the current value of the star again, which will be “Tom Hanks”. These steps are repeated for as many items are present on the list. In this case, we have five items, so the loop will run five times. Because no more values are in the list, when the list is exhausted, Python moves to the following line after the loop. In our case, we have nothing after the loop, so the program will end.
Also, when writing your own for loops, you can choose any name for the temporary variable that holds each value in the list. However, choosing a meaningful name representing a single item from the list is helpful. For example, here’s an excellent way to start a for loop for a list of cars, a list of motorcycles, and a general list of items:
for car in cars:
for motorcycle in motorcycles:
for item in list_of_items:
These naming patterns help you follow the action done on each item within a for-loop. Using singular and plural names can help you identify whether a section of code works with a single item from the list or the whole list.
Performing More Actions Within a For Loop
You can perform many more actions to the elements in a for loop. We will do more to our previous by printing a message to each star, saying they are awesome:
stars = ['Tom Cruise', 'Tom Hanks', 'Samuel L. Jackson', 'Harrison Ford', 'Robert Downey Jr.']
for star in stars :
print(f"{star.title()}, you are awesome!")
The difference between this code and the previous one is that each star has a message attached to its name.
The output displays a personalized message for each star in the stars list:
Tom Cruise, you are awesome!
Tom Hanks, you are awesome!
Samuel L. Jackson, you are awesome!
Harrison Ford, you are awesome!
Robert Downey Jr., you are awesome!
You can also write as many lines of code as you like in the for loop. Every indented line under the line “for star in stars” is considered to be inside the loop. Each indented line is executed once for each item in the list. Therefore, you can perform as many tasks as you like with each item on the list. Let’s add a second line to our message, telling each star that we are looking forward to their next movie:
stars = ['Tom Cruise', 'Tom Hanks', 'Samuel L. Jackson', 'Harrison Ford', 'Robert Downey Jr.']
for star in stars :
print(f"{star.title()}, you are awsome!")
print(f"I can't wait to see your next movie, {star.title()}.\n")
Since both print statements were indented, every line will be executed once for every star in the list. The newline character “\n” in the second print statement inserts a blank line after each iteration of the loop. This will create sets organized of messages for every star in the list:
Result:
Tom Cruise, you are awesome!
I can't wait to see your next movie, Tom Cruise.
Tom Hanks, you are awesome!
I can't wait to see your next movie, Tom Hanks.
Samuel L. Jackson, you are awesome!
I can't wait to see your next movie, Samuel L. Jackson.
Harrison Ford, you are awesome!
I can't wait to see your next movie, Harrison Ford.
Robert Downey Jr., you are awesome!
I can't wait to see your next movie, Robert Downey Jr..
What to do after a for loop in Python?
Once a for loop has completed its task, you’d usually like to summarize the results or move on to tasks your program needs to perform. Any code after the for loop, which is not indented, is executed only once, without repetition. For instance, if you like to thank a group of stars for their movies, you can write a group message thanking them and display it after all the unique messages have been printed. You would position the thank you message after the for loop without any indentation to accomplish this.
stars = ['Tom Cruise', 'Tom Hanks', 'Samuel L. Jackson', 'Harrison Ford', 'Robert Downey Jr.']
for star in stars :
print(f"{star.title()}, you are awsome!")
print(f"I can't wait to see your next movie, {star.title()}.\n")
print("Thank you, everyone for your movies")
Output:
Tom Cruise, you are awsome!
I can't wait to see your next movie, Tom Cruise.
Tom Hanks, you are awsome!
I can't wait to see your next movie, Tom Hanks.
Samuel L. Jackson, you are awsome!
I can't wait to see your next movie, Samuel L.
Jackson. Harrison Ford, you are awsome!
I can't wait to see your next movie, Harrison Ford.
Robert Downey Jr., you are awsome!
I can't wait to see your next movie, Robert Downey Jr..
Thank you, everyone for your movies
If you’re working with data in Python and want to perform an operation on the entire dataset, using a for loop is a great way to achieve this. For example, if you’re making a game and want to show all the characters on the screen, you can use a for loop to iterate through the list of characters and show each one. Once this loop is ended, you can include an unindented block of code to add a “Play Now” button to the screen after all the characters have been shown.
How to avoid Indentation Errors
Have you ever come across an indentation error while Python Lists? It’s a common mistake that can be easily fixed if you know what to look for. Here are some tips on how to avoid indentation errors in your Python codes.
- Be consistent with your indentation: One of the significant reasons why indentation errors occur is inconsistent indentation. Ensure you use the same spaces or tabs for each indentation level. For instance, if you’re using four spaces for one code block, use the same number of spaces for all the code blocks.
- Use a text editor that supports indentation: Most modern text editors can automatically add the correct number of spaces or tabs when you press the “Tab” key. This can save you a ton of time and controls indentation errors.
- Check your code for errors: Constantly double-check your code for errors, especially indentation errors. You can use an online Python code checker to validate your code if uncertain.
Here’s an instance of a code snippet that has an indentation error:
stars = ['Tom Cruise', 'Tom Hanks', 'Samuel L. Jackson', 'Harrison Ford', 'Robert Downey Jr.']
for star in stars :
print(star.title())
Output:
File "<ipython-input-6-973fceb4731a>", line 3
print(star.title())
^
IndentationError: expected an indented block
This post is a more in-depth tutorial on python list data type. By following the above tips, you can avoid this indentation error in your Python code and make your code more legible and maintainable.