In Python, Why Is List[] Automatically Global

In Python, why is list[] automatically global?

It isn't automatically global.

However, there's a difference between rep_i=1 and rep_lst[0]=1 - the former rebinds the name rep_i, so global is needed to prevent creation of a local slot of the same name. In the latter case, you're just modifying an existing, global object, which is found by regular name lookup (changing a list entry is like calling a member function on the list, it's not a name rebinding).

To test it out, try assigning rep_lst=[] in test2 (i.e. set it to a fresh list). Unless you declare rep_lst global, the effects won't be visible outside test2 because a local slot of the same name is created and shadows the global slot.

Why isn't the 'global' keyword needed to access a global variable?

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

def bob():
me = "locally defined" # Defined only in local context
print(me)

bob()
print(me) # Asking for a global variable

The above will give you:

locally defined
Traceback (most recent call last):
File "file.py", line 9, in <module>
print(me)
NameError: name 'me' is not defined

While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

def bob():
global me
me = "locally defined" # Defined locally but declared as global
print(me)

bob()
print(me) # Asking for a global variable

So the above code will give you:

locally defined
locally defined

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

Using append() method on a global list in a function (Python)

Lists are mutable, so while the variable can not be edited (assigned to another list for example) the contents of the list may be modified and the variable will still point to the same list, so the variable is untouched.

Try:

def function():
x = [True]

x = [False] # global variable
function()
print(x)

Using global variables in a function

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1

def print_globvar():
print(globvar) # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar() # Prints 1

Since it's unclear whether globvar = 1 is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global keyword.

See other answers if you want to share a global variable across modules.

Python: How to declare a global array of zeros depending on the input of the user?

There are two ways to do this - globals vs. arguments.

Using the global keyword allows you to access the global instance of order and inv within a function.

inv = []   # global var counts all inversion at level n
order = [] # global var counts all ordered elements at level n

def foo():
# Using order and inv here
global order
global inv

def main():
global order
global inv
# Save Input in variable in n
n = map(int, raw_input().split())
order = [0]*n
inv = [0]*n

The way I would recommend doing it is to declare order and inv within your main function and then pass them as arguments to the foo() or any other function that needs them.

def foo(list_order, list_inv):
# Using order and inv here

def main():
# Save Input in variable in n
n = map(int, raw_input().split())
order = [0]*n
inv = [0]*n
foo(order, inv)

Global dictionaries don't need keyword global to modify them?

The reason is that the line

stringvar = "bar"

is ambiguous, it could be referring to a global variable, or it could be creating a new local variable called stringvar. In this case, Python defaults to assuming it is a local variable unless the global keyword has already been used.

However, the line

dictvar['key1'] += 1

Is entirely unambiguous. It can be referring only to the global variable dictvar, since dictvar must already exist for the statement not to throw an error.

This is not specific to dictionaries- the same is true for lists:

listvar = ["hello", "world"]

def listfoo():
listvar[0] = "goodbye"

or other kinds of objects:

class MyClass:
foo = 1
myclassvar = MyClass()

def myclassfoo():
myclassvar.foo = 2

It's true whenever a mutating operation is used rather than a rebinding one.



Related Topics



Leave a reply



Submit