Salvatore Lopiparo

Senior Software Engineer

Super Simple Python #7 – The for Loop

Last time we learned about lists and how to manipulate the list itself. This time we’ll learn how to do things to items in the list with the for statement.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

First, let’s make a list we can do things to.

1
2
3
>>> grocery_list = ['milk', 'apples', 'orange juice', 'paper towels', 'bbq sauce', 'eggs']
>>> print(grocery_list)
['milk', 'apples', 'orange juice', 'paper towels', 'bbq sauce', 'eggs']

Trying to do your shopping with the items listed like that would be quite difficult. Let’s try printing them in a better format using the for statement!

1
2
3
4
5
6
7
8
9
>>> for grocery_item in grocery_list:
...     print('- ' + grocery_item)
...     
- milk
- apples
- orange juice
- paper towels
- bbq sauce
- eggs

Pretty simple, yeah? When reading the lines above, we say “For each grocery_item in grocery_list, do some stuff (in this case, print the item). The word after for is the variable used for each item in the list, one after another. Using the for statement saves you from writing a lot of extra code, and handles lists of different sizes:

1
2
3
4
5
6
7
8
9
>>> print('- ' + grocery_list[0])
- milk
>>> print('- ' + grocery_list[1])
- apples
>>> print('- ' + grocery_list[2])
- orange juice
>>> print('- ' + grocery_list[3])
- paper towels
>>> # and so on...

We can make something more interesting too. Let’s say we have a bank account and a list of transactions.

1
2
>>> account_balance = 1000
>>> transactions = [-3, -149, -3, -3, -12, -3, -699, -3]

Now we can report each transaction and subtract it from our account balance using a for statement:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> account_balance = 1000
>>> for transaction in transactions:
...     print("Transaction processed: " + str(transaction))
...     account_balance = account_balance + transaction
...     print("Remaining Balance: " + str(account_balance))
...     
Transaction processed: -3
Remaining Balance: 997
Transaction processed: -149
Remaining Balance: 848
Transaction processed: -3
Remaining Balance: 845
Transaction processed: -3
Remaining Balance: 842
Transaction processed: -12
Remaining Balance: 830
Transaction processed: -3
Remaining Balance: 827
Transaction processed: -699
Remaining Balance: 128
Transaction processed: -3
Remaining Balance: 125

Leave a Reply