Python Forum
Why does this work and this doesnt=
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does this work and this doesnt=
#1
x = [0,0]
print(x)
def incrment():
  x[0] = 1
  x[1] = 2
incrment()
print(x)

y = [0,0]
print(y)
def increment():
  y = [1,2]
increment()
print(y)
why does the first code work and the second doesnt!!
Reply
#2
Everything works fine! In case of x-variable 'incrementation', when you call increment(), x[0] = 1 uses x-object from outer scope, exactly, x[0]=1 is equivalent for x.__setitem__(0, 1), but there is no x-object in the increment function, so, x.__setitem__(0, 1) uses x-object from global/outer scope, and x (from outer scope) becomes equal to [1,2]

In case of y variable you perform assignment y=[1,2], this lead to creation of local variable y, that is visible only inside the increment function. Therefore, y-variable from global/outer scope doesn't change.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  pip install requests doesnt work misodca 10 39,658 Sep-24-2025, 02:48 PM
Last Post: DeaD_EyE
  equalto validator doesnt work robertkwild 1 1,446 Jun-02-2024, 06:16 AM
Last Post: Pedroski55
  print doesnt work in a function ony 2 1,640 Mar-11-2024, 12:42 PM
Last Post: Pedroski55
  Pydoc documentation doesnt work Cosmosso 5 8,567 Nov-25-2023, 11:17 PM
Last Post: vidito
  Ldap3 Python print(conn.entries) doesnt work ilknurg 15 13,763 Dec-28-2022, 11:22 AM
Last Post: shad
  pip install pystyle doesnt work person_probably 2 4,925 Sep-23-2022, 02:59 PM
Last Post: person_probably
  Why doesnt chunk generation work? LotosProgramer 1 3,048 Apr-02-2022, 08:25 AM
Last Post: deanhystad
  if conditions in the for indentation doesnt work ? Sutsro 6 6,250 Jun-15-2021, 11:45 PM
Last Post: bowlofred
  I have two Same Code but One of them Doesnt Work beginner721 6 5,393 Jan-22-2021, 10:56 PM
Last Post: beginner721
  BEGINNER: My calculator doesnt work iskov 5 5,286 Oct-09-2019, 07:45 AM
Last Post: buran

Forum Jump:

User Panel Messages

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