Python Forum
Why doesn't list require global keyword?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why doesn't list require global keyword?
#3
This does assignment.
 dog += 1
This does not:
numbers.append(x)
"global" only affects assignment.

Normally when you assign a value to a variable, it looks for the variable in the local scope. If the variable does not exist, one is created.
Declaring a variable as global tells python to look for the variable in the global scope instead of local scope. If the variable does not exist, one is created in the global scope.

appending a value to a list modifies an existing object, it does not assign a list object to a variable. This code does assignment with a list and requires a global declaration.
def enter_number(x):
global numbers
numbers = [x]
Reply


Messages In This Thread
RE: Why doesn't list require global keyword? - by deanhystad - Jan-15-2024, 01:16 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extending list doesn't work as expected mmhmjanssen 2 285 May-09-2024, 05:39 PM
Last Post: Pedroski55
  Find a specific keyword after another keyword and change the output sgtmcc 5 957 Oct-05-2023, 07:41 PM
Last Post: deanhystad
  Why doesn't calling a parent constructor work with arbitrary keyword arguments? PurposefulCoder 4 1,049 Jun-24-2023, 02:14 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 1,695 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  How to make global list inside function CHANKC 6 3,238 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  Pattern Require Last Line Print() why? Harshil 4 2,520 Aug-08-2020, 04:54 PM
Last Post: Harshil
  Require Some Suggestions gouravlal 2 1,949 Jul-27-2020, 06:14 AM
Last Post: gouravlal
  search binary file and list all founded keyword offset Pyguys 4 2,887 Mar-17-2020, 06:46 AM
Last Post: Pyguys
  Where to put the global keyword when assigning variables outside a function? new_to_python 8 3,148 Feb-09-2020, 02:05 PM
Last Post: new_to_python
  Global variable does not seem to be global. Columbo 6 3,818 Jul-15-2019, 11:00 PM
Last Post: Columbo

Forum Jump:

User Panel Messages

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