top of page

# Summary

### For Loops

Let's consider a list of 10 numbers, 0 to 9:

1 my_list 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

print(my_list)

It would be easier if we didn't have to type out each number (computers should be able to count, shouldn't they?). There is a convenient function, list(range()), that allows us to create a list containing every number between a specified start and stop.

1 my_list = list(range(0, 10))

print(my_list)

Try it yourself here!

Now that we have lists of numbers, what if we wanted to execute the same function to every element in the list? For example, we can add 5 to each element in my_list with a simple operation. In computer science, a for loop allows code to be executed repeatedly (in this case, the code we want to execute repeatedly adds 5 to each element in the list).

â€‹

Every for loop starts with the same syntax:

1 my_list = list(range(0, 10))

for my_number in my_list:

3     print(my_number + 10)

Predict what you think the output of this code will be and then check

bottom of page