What can we do with each item in a list in a for loop?

Question

What can we do with each item in a list in a for loop?

Answer

For loops are great for doing something to every item in a list. So good, in fact, that they built this handy syntax into the language itself! In other programming languages, doing this for item in list is not so simply written!
In this exercise, that something we want to do each time is to multiply the item by 2. But you could do whatever you wanted to each item each time it loops.
To demonstrate how item becomes the next item in the list after every time it loops, take a look at the code below:

my_list = [1, 2, 3, 4]

for item in my_list:
  print item  # displays the current item in the list

This will print:

1
2
3
4
2 Likes

I was playing around with for loops so I can get more comfortable with them outside of the exercise.

I tried to use the variable that was defined in the for loop outside of it and it did work but the answer it printed to the console does not make sense. I was curious as to what it would print since it was coming from a list of 6 integers, but it only printed a single number. Any reason that this was the answer I got?

MY CODE:

my_list = [1,9,3,8,5,7]

for number in my_list:
print 2 * number

print str(number) + “who”

HERE IS WHAT CONSOLE PRINTED
2
18
6
16
10
14
7who

2 Likes

Nothing out of the ordinary there. It outputs exactly as expected.

2 Likes

Ya i realized after where I was making the mental error. I thought it may print all of the numbers from my_list when I typed print str(number), but realized it only printed the last value from the list which makes sense.

2 Likes

How ? i still don’t get as to why all the numbers didn’t get printed ?

3 Likes

number is a single value, an integer. To print all the numbers in the list,

print (my_list)
2 Likes

In the code below,

my_list = [1,9,3,8,5,7]

for item in my_list:

print 2*item

it seems we can replace the number variable with some other name e.g., item. I was wondering what defines number/item therein.

Variable names are arbitrarily chosen and hopefully reflect what the object represents. The floor is wide open. Generally, we use a name with the clearest meaning.

Above we have a list of numbers, so, number is an apt choice since it describes the value it references. The elements can just as easily be referred to as items, so item is okay, though ambiguous since item could be any object, not just a number.

Bottom line, variables are defined when we give then something to reference (set them with an assignment). Clarity (clear meaning) helps both us and other readers understand and follow our code.

4 Likes

Thank you so much for the explanation.

1 Like

I still could not understand the reason why the output for print str(number) is 7 and not another number?

It is a string representation of the number given in the argument. If you check its type you’ll find that it is now a string, but still the character, ‘7’.

1 Like