Python Forum
Example of list comprehensions doesn't work
Thread Rating:
  • 2 Vote(s) - 1.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Example of list comprehensions doesn't work
#11
You get a
Error:
UnboundLocalError: local variable 'z' referenced before assignment
The cause is, you're referencing z before it has been assigned.
In this case it doesn't matter, that the name z is global.
In the context of the list comprehension the name z is a local variable, because it's assigned.
You may ask now, where the assignment happens:

for z in range(z+1)

The red one, is the assignment of local variable z. The green is read access to the variable.
Just change the z into z_ and the code works.

print([[x,y,z_] for i in range(x+1) for j in range(y+1) for z_ in range(z+1)])
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Example of list comprehensions doesn't work - by DeaD_EyE - May-14-2018, 09:03 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extending list doesn't work as expected mmhmjanssen 2 191 May-09-2024, 05:39 PM
Last Post: Pedroski55
  Why doesn't list require global keyword? johnywhy 9 939 Jan-15-2024, 11:47 PM
Last Post: sgrey
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 999 Jun-24-2023, 02:14 PM
Last Post: deanhystad
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,414 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Beginner: Code not work when longer list raiviscoding 2 863 May-19-2023, 11:19 AM
Last Post: deanhystad
  Why doesn't this code work? What is wrong with path? Melcu54 7 1,896 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  How to work with list kafka_trial 8 2,098 Jan-24-2023, 01:30 PM
Last Post: jefsummers
  color code doesn't work harryvl 1 937 Dec-29-2022, 08:59 PM
Last Post: deanhystad
  convert this List Comprehensions to loop jacklee26 8 1,564 Oct-21-2022, 04:25 PM
Last Post: deanhystad
  client.get_all_tickers() Doesn't work gerald 2 1,758 Jun-16-2022, 07:59 AM
Last Post: gerald

Forum Jump:

User Panel Messages

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