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
  Why doesnt chunk generation work? LotosProgramer 0 168 Jun-18-2021, 01:13 PM
Last Post: LotosProgramer
  if conditions in the for indentation doesnt work ? Sutsro 6 1,103 Jun-15-2021, 11:45 PM
Last Post: bowlofred
  I have two Same Code but One of them Doesnt Work beginner721 6 609 Jan-22-2021, 10:56 PM
Last Post: beginner721
  code doesnt return anything ofrihemo 3 741 Jun-30-2020, 05:14 PM
Last Post: ofrihemo
  Pydoc documentation doesnt work Cosmosso 4 1,446 Dec-13-2019, 08:21 AM
Last Post: Cosmosso
  multiprocessing doesnt contain some modules(shared_memory) mike000 3 780 Oct-31-2019, 02:20 PM
Last Post: mike000
  BEGINNER: My calculator doesnt work iskov 5 1,076 Oct-09-2019, 07:45 AM
Last Post: buran
  Why this simple function doesnt work? blackknite 8 1,541 Jan-05-2019, 12:32 PM
Last Post: buran
  why doesnt the while loop run? supermane 3 1,420 Aug-04-2018, 06:01 AM
Last Post: wavic
  Discord Bot doesnt work when opened with windows himdipie 0 1,335 Apr-15-2018, 04:48 PM
Last Post: himdipie

Forum Jump:

User Panel Messages

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