Python Forum
Prevent Variable Referencing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Prevent Variable Referencing
#1
I don't know how to explain it very well, but I've been trying to figure this out for a few days and I haven't had any luck with fixing it.

The following code is supposed to append a lambda to a list, so that the function the lambda calls can be called later on. NOTE: this isn't my actual code, but a proof of concept that works in the same way.
def foo(bar):
	print(bar)

li = []

for i in range(10):
	li.append(lambda: foo(i))
Later I can call the functions using this chunk of code.
for func in li:
	func()
When I run this, instead of steadily incrementing, it just uses the last value of i.
Output:
9 9 9 9 9 9 9 9 9 9
I understand that this is due to how python handles variable referencing, but I want to know if there is a way to bypass this and only get the value of i without referencing it.
Reply


Messages In This Thread
Prevent Variable Referencing - by Th3Eye - Oct-03-2018, 04:48 PM
RE: Prevent Variable Referencing - by ichabod801 - Oct-03-2018, 04:56 PM
RE: Prevent Variable Referencing - by buran - Oct-03-2018, 04:56 PM
RE: Prevent Variable Referencing - by Th3Eye - Oct-03-2018, 06:58 PM
RE: Prevent Variable Referencing - by buran - Oct-03-2018, 07:01 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Using SQLAlchemy, prevent SQLite3 table update by multiple program instances Calab 2 1,853 Aug-09-2023, 05:51 PM
Last Post: Calab
Smile How we can prevent screen recording murad_ali 3 4,121 Jul-29-2022, 10:29 AM
Last Post: DeaD_EyE
  name 'lblstatus' is not defined when referencing a label KatManDEW 4 3,049 Apr-21-2022, 12:33 PM
Last Post: KatManDEW
  How to prevent python from going to new line in for loop? idknuttin 3 7,790 Feb-11-2022, 05:40 AM
Last Post: deanhystad
  Dictionary Referencing nickdavis2017 1 2,331 Nov-20-2021, 06:24 PM
Last Post: deanhystad
  Referencing string names in df to outside variables illmattic 1 2,002 Nov-16-2021, 12:47 PM
Last Post: jefsummers
  Prevent urllib.request from using my local proxy spacedog 0 3,913 Apr-24-2021, 08:55 PM
Last Post: spacedog
  Referencing a fixed cell Mark17 2 2,860 Dec-17-2020, 07:14 PM
Last Post: Mark17
Sad need help in referencing a list n00bdev 2 2,598 Nov-01-2020, 12:06 PM
Last Post: buran
  Issue referencing new instance from other class nanok66 3 3,132 Jul-31-2020, 02:07 AM
Last Post: nanok66

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020