Looping through Python data structures

Python for MATLAB Users

Justin Kiggins

Product Manager

How for loops work in Python

MATLAB

for i=1:5
  disp(i);
end
disp('done');
1
2
3
4
5
done

Python

for i in [1, 2, 3, 4, 5]:
    print(i)
print('done')
1
2
3
4
5
done
Python for MATLAB Users

Looping through a list of strings

groceries = ['bread', 'tea', 'banana']

print(groceries)
['bread', 'tea', 'banana']
for item in groceries:
    print(item)
bread
tea
banana
Python for MATLAB Users

Looping through a dictionary

abbreviations = {'New York': 'NY',
                 'California': 'CA',
                 'Illinois': 'IL',
                 'Texas': 'TX'}
print(abbreviations)
{'New York': 'NY', 'California': 'CA', 'Illinois': 'IL', 'Texas': 'TX'}
for state, abbv in abbreviations.items():
    print(state, abbv)
New York NY
California CA
Illinois IL
Texas TX
Python for MATLAB Users

Looping through a 1D NumPy array

import numpy as np
arr = np.array([1, 2, 3])
print(arr)
[1 2 3]
for element in arr:
    print(element)
1
2
3
Python for MATLAB Users

Looping through a 2D NumPy array

import numpy as np
X = np.array([[1, 2, 3], [4, 5, 6]])
print(X)
[[1 2 3]
 [4 5 6]]
for row in X:
    print(row)
[1 2 3]
[4 5 6]
Python for MATLAB Users
import pandas as pd
d = [{'fruit': 'apple', 'color': 'red'},
     {'fruit': 'banana', 'color': 'yellow'},
     {'fruit': 'pear', 'color': 'green'}]
df = pd.DataFrame(d)
print(df)
    color   fruit
0     red   apple
1  yellow  banana
2   green    pear
for ii, row in df.iterrows():
    print(ii, row['fruit'], row['color'])
0 apple red
1 banana yellow
2 pear green
Python for MATLAB Users

Let's practice!

Python for MATLAB Users

Preparing Video For Download...