# Intermediate Python for Data Science: Looping Data Structure

After the matplotlib for visualization, introduction to dictionaries and Pandas DataFrame, follows by logical, Boolean and comparison operators with if-elif-else control flow and now, comes to the last part, the while loop, for loop and loop for a different data structure.

In Python, some of the objects are iterable which means it loops through the object in a list, for example, to get each element. It loops through a string to capture each character in the string. A for loop iterates over a collection of things and while loop can do any kind of iteration within the block of codes, while some condition remains True

## For Loop

The main keywords are for and in. It uses along with colon (:) and indentation (whitespace). Below is the syntax,

```#loop statement
my_iterable = [1,2,3]
for item_name in my_iterable:
print(item_name)
```

I used two iterator variables (index, area) with enumerate(), for example, the sample code below. enumerate() loops over something and has an automatic counter, then returns an enumerate object.

```# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Change for loop to use enumerate() and update print()
for index, area in enumerate(areas) :
print("room " + str(index) + ": " + str(area))

#Output:
"""
room 0: 11.25
room 1: 18.0
room 2: 20.0
room 3: 10.75
room 4: 9.5
"""
```

Another example utilizes a loop that goes through each sublist of house and prints out the x is y sqm, where x is the name of the room and y is the area of the room.

```# house list of lists
house = [["hallway", 11.25],
["kitchen", 18.0],
["living room", 20.0],
["bedroom", 10.75],
["bathroom", 9.50]]

# Build a for loop from scratch
for x in house:
print("the " + str(x[0]) + " is " + str(x[1]) + " sqm")

# Output:
"""
the hallway is 11.25 sqm
the kitchen is 18.0 sqm
the living room is 20.0 sqm
the bedroom is 10.75 sqm
the bathroom is 9.5 sqm
"""
```

Definition of enumerate() can be found here. My post on for loop is here.

## While Loop

The main keyword is while, colon (:) and indentation (whitespace). Below is the syntax,

```# while loop statement
while some_boolean_condition:
# do something

# Examples
x = 0
while x < 5:
print(f'The number is {x}')
x += 1
```

An example of putting an if-else statement inside a while loop.

```# Initialize offset
offset = -6

# Code the while loop
while offset != 0 :
print("correcting...")
if offset > 0:
offset = offset - 1
else:
offset = offset + 1
print(offset)

# Output:
"""
correcting...
-5
correcting...
-4
correcting...
-3
correcting...
-2
correcting...
-1
correcting...
0
"""
```

My post on while loop is here.

## Loop Data Structure

Dictionary:
If you want to iterate over key-value pairs in a dictionary, use the items() method on the dictionary to define the sequence in the loop.

```for key, value in my_dic.items() :
```

Numpy Array:
If you want to iterate all elements in a Numpy array, use the nditer() function to specify the sequence.

```for val in np.nditer(my_array) :
```

Some examples as below:

```# Definition of dictionary
'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }

# Iterate over europe
for key, value in europe.items():
print("the capital of " + key + " is " + value)

# Output:
the capital of austria is vienna
the capital of norway is oslo
the capital of italy is rome
the capital of spain is madrid
the capital of germany is berlin
the capital of poland is warsaw
the capital of france is paris
"""

# Import numpy as np
import numpy as np

# For loop over np_height
for x in np_height:
print(str(x) + " inches")

# For loop over np_baseball
for x in np.nditer(np_baseball):
print(x)

```

Loop over DataFrame explanation and example can be found in my post here.