A For Loop is a method of iterating through a string, list, dictionary, data frame, series, or anything else that you would like to iterate through. To iterate means to go through an item that makes up a variable. What the item type is depends on what you are iterating through.

The structure of a For Loop looks like this:

for item in variable:
    do_something

 

To iterate through a:

  • String, is to go letter by letter
str = "Michigan"

for letter in str:
    print(letter)
M
i
c
h
i
g
a
n

 

  • List, is to go entry by entry
lst = ['Apples', 'Cherries', 'Blueberries']

for item in lst:
    print(item)
Apples
Cherries
Blueberries

 

  • Dictionary, is go through key by key, value by value, or key value by key value. If unfamiliar with dictionaries, we have a section for that!
    • The key is the item before the colon, “:”, and the value is the item after the the colon. It looks like this “key : value”.
dct = {"key" : "value", "Summer" : "Hot", "Red Wings" : "Hockey"}

for key, value in dct.items():
    print(key)
Summer
key
Red Wings

 

dct = {"key" : "value", "Summer" : "Hot", "Red Wings" : "Hockey"}

for key, value in dct.items():
    print(value)
Hot
value
Hockey

 

dct = {"key" : "value", "Summer" : "Hot", "Red Wings" : "Hockey"}

for key, value in dct.items():
    print(key, value)
Summer Hot
key value
Red Wings Hockey

 

  • Data frame, is to go through row by row or column by column. If unfamiliar with data frames, we have a section for that too!
    • First, we need a data frame to work with!
df = pd.DataFrame([['Samantha','F',28], ['Corey', 'M', 28], ['Maddi', 'F', 6]], columns= ['Name', 'Sex', 'Age'])

 

Let’s see what the data frame looks like.

Index Name Sex Age
0 Samantha F 28
1 Corey M 28
2 Maddi F 6

By default, iterating through a data frame will iterate over the columns

for entry in df:
    print(entry)
Name
Sex
Age

 

In order to iterate over the rows, we have to call the .iterrows() method. In addition, we need to identify which series (a.k.a. a column) we want to get the values from. If we don’t identify which series we are interested in, Python will output each observation will all the column values associated with that observation.

for index, entry in df.iterrows():
    print(entry['Name'])
Samantha
Corey
Maddi

 

  • Series, is to go through observation by observation. If unfamiliar with series, we have a section for that!
    • Iterating through a series is identical to iterating through the rows of a data frame with the column identified- the Python code just looks different
for entry in df['Name']:
    print(entry)
Samantha
Corey
Maddi

 

For Loop within a For Loop

You can have a For Loop within a For Loop. By implementing this technique, Python will iterate through the item(s) that make up that item. This will be demonstrated by using our lst example with the item in the first index (first row or first observation).

for item in lst[0]:
    for letter in item:
        print(letter)
A
p
p
l
e
s