# Linking variables: for X in Y

#1

Hey everyone,

I hope that I can get someone to help me explain the use of the "for X in Y" part of the code. Here is my current code (with my question embedded in the code as well):

``````shopping_list = ["banana", "orange", "apple"]

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

def compute_bill(food):
total = 0
for X in food: #How are the X variables linked?
total += X
n = shopping_list]
print sum(n)``````

What I am interesting in understanding better is how python links variables in the "for X in Food". So I far I believe that second variable (Food) should be the place where I retrieve data from but how does the first variable connect?

#2

Python will ask the iterable (Y) for one value at a time and assign each to your specified variable (X) as the loop goes, one at a time.

It goes a bit like this (and this is valid code)

``````Y = range(4)

iterator = iter(Y)
while True:
try:
X = next(iterator)
# run the code in the loop
print X
except StopIteration:
# the iterator has been exhausted, end of loop
break``````

#3

Thank you for the fast response,

Let me see if I got it right. Said in other words, "for X in Y" means that:

Y is the list that you draw from and X is just what is looped through. You can basically name it as you please and use that as the variable name for further processing?

#4

The loop assigns each element provided by Y, into X, yes.

So if you do

``X = 5``

Then that has no effect what-so-ever on the iterable.

But if you make a change to X, that'll change the element in the iterable, like:

``X += [7]``

(+= is in-place add, so if X were a lists (for example if Y is a 2D list), then you could do the above)

So X refers to the element - this is the way all variables work - they are references to the values which is saying that multiple variables can refer to the same value.

#5

Oh and note that += still won't change the value if it's immutable, for example an integer.

example:

mutable, for example lists

``````a = []
b = a
b += [1]
print a # [1]``````

immutable, for example ints

``````a = 3
b = a
b += 5
print a # 3
print b # 8``````