Dex&#39; ter - 2 years ago 52
Python Question

# Output that looks like something else in Python

Today I had some free time and I started to play a little bit with Python. I tried running an apparently simple piece of code which looks like this:

``````a = []
for i in range(10):
a.append(i * ++i)
for a[i] in a:
print(a[i])
``````

Now, as you probably may expect, the obvious output should be something like:

``````0
1
4
9
16
25
36
49
64
81
``````

But it actually isn't. What I do get instead when I run it, is:

``````0
1
4
9
16
25
36
49
64
64
``````

How is this working ?

Let's break it down to pieces.

``````a = []
``````

Empty list initialized, so far, so good.

``````for i in range(10):
a.append(i * ++i)
``````

Two mistakes here. First of all, `++i` is `+(+i)` which essentially is no op. Secondly, any changes done inside for-loop body for `i` name won't survive to next iteration.

`for o in seq` essentially does this:

1. Pointer is kept internally and this is where it keeps track of currently "active" member in iteration
2. On beginning of each loop

a) pointer is incremented to next element

b) value of that element is assigned to `o`

So in this step, on beggining of each iteration `range(10)` is asked for next number and `i = THAT_NEXT_NUMBER` assignment is done.

Now let's go to that bizzare second loop:

``````for a[i] in a:
print(a[i])
``````

We know that after first loop `i` is 9 (last value assigned to name `i`) and `a` is `[0, 1, 4, 9, 16, 25, 46, 49, 64, 81]`.

Since for loop is essentially "ask and assign" described above, step by step operations are:

1. Ask list for first element, assign it to `a[i]` which is `a[9]`, go to for-loop body. List is: `[0, 1, 4, 9, 16, 25, 46, 49, 64, 0]`, printed value is `a[i]` = `a[9]` = `0`
2. Ask list for second element, assign it to `a[i]` which is `a[9]`, go to for-loop body. List is: `[0, 1, 4, 9, 16, 25, 46, 49, 64, 1]`, printed value is `a[i]` = `a[9]` = `1`

1. Ask list for second-to-last element, assign it to `a[i]` which is `a[9]`, go to for-loop body. List is: `[0, 1, 4, 9, 16, 25, 46, 49, 64, 64]`, printed value is `a[i]` = `a[9]` = `64`
2. Ask list forlast element, assign it to `a[i]` which is `a[9]`, go to for-loop body. List is: `[0, 1, 4, 9, 16, 25, 46, 49, 64, 64]` (9th element in list is replaced with 9th element in list), printed value is `a[i]` = `a[9]` = `64`.