Iteration variables in for loops

Hi there,

I am here: Python for Data Science: Fundamentals - Lists and For Loops - Page 9

I am clear that the “iterable variable” is the ‘file’ name or variable name, where the info is stored but I am wondering what the criteria is to choose the “iteration variable” in a for loop? If I want to do the iteration process on a row then I type “row” and if a want to do the iteration process in a value do I just type "value”? or is there a predetermined code list for iteration variables that I should be aware of?

Here is the code with the iteration variables in question bolded:

for row in app_data_set:
rating=row[-1]
rating_sum= rating_sum+rating
print(rating_sum)

Thank you so much!

Hi,
There are already few answers on this topic here, on the forum.

  1. Iterator in For-loops
  2. How does a For Loop Work?

If they will not be enough, feel free to ask for additional explanaton.

2 Likes

The iterable is not a file name necessarily. It’s more like “an object on which you can iterate”. That may seem like splitting hairs but it’s an important distinction.

The word you decide to use at the start of a for loop is a placeholder for each item in the iterable, in your example row. Changing the word/name does not change the functionality. You could replace it with value, or smurf, or whatever: the iteration variable will take the value of each item in an iterable in turn.

As an example:

x = ["item1", "item2", "item3"]
for smurf in x:
    print(smurf)

The output would be:

item1
item2
item3

The key becomes understanding which iterable you are using in a loop. For a list, it’s elementary. For a dictionary, you may loop over keys, or values, or both. Documentation will help you understand what options you have when working with different types of iterables.

2 Likes

Super helpful thank you so much!

1 Like