Mastering Python Basics: Understanding For Loops in Lists
Written on
Chapter 1: Introduction to For Loops
It's time to explore the concept of "for loops," a fundamental tool in Python that simplifies working with lists containing multiple elements. This powerful construct helps eliminate redundancy in coding, making it easier to process large datasets.
Traveling? Avoid hefty roaming fees with Saily eSIM from NordVPN and NordPass Creators.
This article is part of the "Start Coding with Python" series (see the complete list).
Section 1.1: Basic Example of a For Loop
Let's create a brief Python script named friends.py:
# The lines beginning with # are comments that Python ignores.
# file name: friends.py
friends = ['Elliot', 'Angela', 'Tyrell']
print(friends[0])
print(friends[1])
print(friends[2])
When we execute this code, it will display each name in the friends list:
$ python3 friends.py
Elliot
Angela
Tyrell
While this example only contains three names and is manageable, imagine handling a list with hundreds of entries. Here, a for loop becomes invaluable, allowing us to streamline our code. Let's revise the earlier code using a for loop:
# file name: friends.py
friends = ['Elliot', 'Angela', 'Tyrell']
for friend in friends:
print(friend)
In this case, the line for friend in friends: iterates through the friends list, assigning each element to the variable friend. Python then prints the value associated with friend and continues this process for every item in the list. You can think of this as, "For each friend in the list, print their name."
Section 1.2: Understanding Variable Naming
As we start our for loop, a new variable called friend is introduced, but it could be named anything you prefer:
# file name: friends.py
friends = ['Elliot', 'Angela', 'Tyrell']
for anything in friends:
print(anything)
Running the code again yields the same result:
$ python3 friends.py
Elliot
Angela
Tyrell
However, it's clear that using a descriptive variable name like friend is more intuitive given the context. While Python doesn't mind the name, clarity is beneficial for us as programmers.
Section 1.3: Delving Deeper into For Loops
For those who are new to coding, let’s examine the for loop more closely. Starting from the line:
for friend in friends:
Python retrieves the first entry from the friends list, which is "Elliot", and assigns it to the variable friend. The next line:
print(friend)
prints the current value of friend, which is "Elliot." Subsequently, Python returns to the start of the loop and retrieves the next item, "Angela," associating it with friend and printing it in the same manner. This process continues until all elements are processed.
As you become comfortable with for loops, you can create more complex scripts using concepts learned in previous lessons:
# file name: friends.py
friends = ['Elliot', 'Angela', 'Tyrell']
for friend in friends:
print(f"Bon Soir, {friend}!")
print(f"See you later, {friend}.n")
Running this code will yield:
$ python3 friends.py
Bon Soir, Elliot!
See you later, Elliot.
Bon Soir, Angela!
See you later, Angela.
Bon Soir, Tyrell!
See you later, Tyrell.
Thank you, everyone!
Lastly, in the above code, indentation is not merely a stylistic choice; it is crucial in Python, as shown here:
for friend in friends:
print(friend)
Proper indentation helps Python interpret the structure of your code. Errors in indentation are common, such as mistakenly indenting lines that don’t require it or neglecting to indent those that do. Familiarizing yourself with these potential pitfalls now will aid in preventing them later in your programming journey.
Chapter 2: Additional Resources and Best Practices
The first video, "Python Tutorial 2016 Lesson 1.3 - For Loops and List Data," provides a great introduction to for loops and their application in handling lists.
The second video, "Python 3 Tutorial for Beginners #9 - For Loops," further explores for loops, making it easier for beginners to grasp this essential concept.
For more insights, consider checking out Eric Matthes' "Python Crash Course," which is an excellent resource for further learning.
References:
[1] Python Crash Course 3rd ed., Eric Matthes, (shop online & buy the book).
[2] Python Programming and Computer Programming.
Support me at no extra cost & even save money when you shop online: visit My Affiliate Storefront, where you can find 50% Off Promo Codes. Secure your network and online privacy with NordVPN (69% Off limited time deal) and NordPass Premium (50% Off limited time offer), both offering a 30-day money-back guarantee!
Photo by Glenn Carstens-Peters on Unsplash.
This post includes affiliate links. If you click on any of them and make a purchase, I may earn a commission at no extra cost to you. Please support me with as little as $1 (no sign-ups required! Just Tap & Tip).