Mastering Python For Loops
Python Sequence Iteration
Walking Through Sequences
In programming, you often need to perform the same action on every item in a collection. Python's for loop is the primary tool for this job. It lets you walk through a sequence, like a string or a list, and handle each element one at a time.
The structure is simple and readable. It always follows the same pattern.
for item in sequence:
# Do something with item
Let's break that down:
forandinare required keywords. Theinkeyword is what connects the temporary variable to the sequence.itemis a temporary variable you create. In each pass of the loop, Python assigns the next element from the sequence to this variable.sequenceis the data collection you want to iterate over. This could be a string, a list, or a tuple.- The colon
:at the end is crucial. It signals the start of an indented block of code.
Python uses indentation, typically four spaces, to define which lines of code belong inside the loop. This is a core part of the language's syntax. Any code that is indented after the colon will be executed for every single item in the sequence.
Iterating Over Strings
A string is just a sequence of characters. A for loop can treat it like one, pulling out each character from beginning to end.
language = "Python"
for char in language:
print(char)
When you run this code, the loop starts with the first character in the string "Python". It assigns 'P' to the char variable and runs the indented code, which prints 'P'.
Then, it automatically moves to the next character, assigns 'y' to char, and prints it. This continues until every character has been processed, producing this output:
P
y
t
h
o
n
Traversing Lists and Tuples
The same logic applies to lists and tuples, which are ordered sequences of items. The loop doesn't care about the data type of the items inside; it just goes through them one by one.
Imagine you have a list of weekly sales figures and you want to calculate the total.
sales_data = [250, 310, 190, 420, 350]
total_sales = 0
for sale in sales_data:
total_sales = total_sales + sale
print(f"Total sales for the week: đź’˛{total_sales}")
In each iteration, the variable sale takes on the value of the next element in sales_data. The loop adds this value to total_sales. After the loop finishes, the final sum is printed. The same syntax works perfectly for tuples as well.
The
forloop syntax is identical for strings, lists, and tuples because they are all iterable sequences. Python handles the mechanics of getting the next item for you.
Now, let's test your understanding of how to iterate through these sequences.
What is the primary role of the in keyword in a Python for loop?
What is the final value of total after this code block is executed?
sales_data = [150, 200, 50]
total = 0
for sale in sales_data:
total = total + sale