ho.s ho.s - 1 year ago 69
Python Question

"Backlog" of a loop through a list in Python

I have a weird Python beginner's question,.. playing around in my virtual env in the interpreter (python 3.5):

I have a list with mixed types:

lissi = ["foo", "bar". "boo", "baz", 4, 7]

And then "accidentally" try to print out all elements in a for loop concatenated to a string:

for x in lissi:
print("Hallo " + x)

This, of course, is not possible bcs. we cannot conc. integers to a String - so the first elements are printed and then there is a TypeError.

Then I typed just
"x" and enter
to see if there is still data stored and yes it is: x is 4.

(tried that to figure out if 7 is also still there).

So my question is: What happens "under the hood" in Python in the for loop: Seems as if every successfully processed element is removed, but there is a backlog stored in x which is the first element the TypeError was thrown for? And is there a way to "clear" this data from memory in case of errors?


Answer Source

It's not a backlog and nothing like "every successfully processed element is removed".
Basically on every iteration for loop assigns to variable x the value of next element of list lissi (doesn't have to be a list, can be any iterable).
Whenever the loop breaks, due to exception or break statement, variable x is left intact, so it contains the last value assigned by the for loop.
This is ok, since loops don't have any isolated scope in Python and actually makes it convenient to search iterable for interesting element, breaking the loop when it's found and not being forced to store it in another variable before leaving the loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download