For loops#

Programming for Geoscientists Data Science and Machine Learning for Geoscientists

for loops are used to iterate over elements in a list (or any other iterable object). Iterating means looping over. The syntax for this type of loop is:

    for element in list:
        # lines of code to be executed

The code will loop over all elements in the list and execute the same code for each of them. The code inside for loop needs to be indented. For example:

my_list = [1, 3, 5, 7, 9, 11]
print(my_list)

# For each element in my_list, add 5 and print it
for element in my_list:
    element += 5
    print(element)

print(my_list)  # The original list does not change
[1, 3, 5, 7, 9, 11]
6
8
10
12
14
16
[1, 3, 5, 7, 9, 11]

Apart from looping over elements,for loops can be created for specified number of iterations using the range() function, which returns an iterable object. The syntax for range() is:

range([start], stop, [step])

This generates sort of a list with elements between start and stop, excluding stop. If step (increment) is not provided, every number is generated. If you use only one argument, range(5) treats it as a stop value and it starts from 0.

print("range(0, 6, 1)")
for i in range(0, 6, 1):
    print(i)
    
print("range(0, 6, 2)")
for i in range(0, 6, 2):
    print(i)
    
print("range(0, 6)")
for i in range(0, 6):
    print(i)
    
print("range(6)")
for i in range(6):
    print(i)
range(0, 6, 1)
0
1
2
3
4
5
range(0, 6, 2)
0
2
4
range(0, 6)
0
1
2
3
4
5
range(6)
0
1
2
3
4
5

We can generate an index with range() function to loop over elements in a list:

my_list = [1, 3, 5, 7, 9, 11]
print(my_list)

for i in range(len(my_list)):  # Range from 0 to length of list
    my_list[i] *= 2  # Modify values in the list
    
print(my_list)    
[1, 3, 5, 7, 9, 11]
[2, 6, 10, 14, 18, 22]

Exercises#


  • Create a for loop to find Celsius temperatures for Fahrenheit temperatures between 20\(^\circ\)F and 80\(^\circ\)F at 5\(^\circ\)F increments. The Fahrenheit-Celsius conversion formula is:

\[ T_{Celsius} = \frac{5}{9}*(T_{Fahrenheit}-32).\]

  • Triangles: We want to create a triangle of \(n\) rows of numbers which looks as follows:

      1
      1 2
      1 2 3
      1 2 3 4 
      1 2 3 4 5
    

HINT: Consider iterating over a range \([1,...n]\)