OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Python, loops and closures

  • Thread starter Thread starter Luca
  • Start date Start date
L

Luca

Guest
I'm a fairly experienced C/C++ (and to some degree, Java) programmer. I'm learning python, but I'm baffled at some strange (for my backgroung) behaviors of the language.

I'm learning about nested function and closures (reading "Learning Python", that seems a really good source for me).

I understand that if I nest a def inside a for loop when I call the created function, it looks up the last value of the captured loop variable (as it captures by reference, as a C++ programmer would put it)

Code:
funcs = []
for i in range(4):
    def f():
        print(i)
    funcs.append(f)

and running the program the result is

Code:
>>> for f in funcs:
      f()


3
3
3
3

Now, I was wrapping my head around this when I stumbled upon this (what to me seems) an inconsistency: if I do

Code:
for i in range(4):
  funcs[i]()


0
1
2
3

more baffling, if I do

Code:
>>> i = 2
>>> funcs[i]()

2

and now, all functions in list returns 2:

Code:
for f in funcs:
  f()


2
2
2
2

there must be some scope related question that I can't grasp
<p>I'm a fairly experienced C/C++ (and to some degree, Java) programmer. I'm learning python, but I'm baffled at some strange (for my backgroung) behaviors of the language. </p>

<p>I'm learning about nested function and closures (reading "Learning Python", that seems a really good source for me).</p>

<p>I understand that if I nest a def inside a for loop when I call the created function, it looks up the last value of the captured loop variable (as it captures by reference, as a C++ programmer would put it) </p>

<pre><code>funcs = []
for i in range(4):
def f():
print(i)
funcs.append(f)
</code></pre>

<p>and running the program the result is</p>

<pre><code>>>> for f in funcs:
f()


3
3
3
3
</code></pre>

<p>Now, I was wrapping my head around this when I stumbled upon this (what to me seems) an inconsistency: if I do</p>

<pre><code>for i in range(4):
funcs()


0
1
2
3
</code></pre>

<p>more baffling, if I do</p>

<pre><code>>>> i = 2
>>> funcs()

2
</code></pre>

<p>and now, all functions in list returns 2:</p>

<pre><code>for f in funcs:
f()


2
2
2
2
</code></pre>

<p>there must be some scope related question that I can't grasp</p>
 

Latest posts

Top