[python] Defining lists as global variables in Python

I am using a list on which some functions works in my program. This is a shared list actually and all of my functions can edit it. Is it really necessary to define it as "global" in all the functions?

I mean putting the global keyword behind it in each function that uses it, or defining it outside of all the functions is enough without using the global word behind its definition?

This question is related to python list global-variables

The answer is


When you assign a variable (x = ...), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:

x = 0
def f():
    x = 1
f()
print x #=>0

and expect 1. Instead, you need do declare that you intend to use the global x:

x = 0
def f():
    global x
    x = 1
f()
print x #=>1

But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.

Also very important: Member assignment (x.name = ...), item assignment (collection[key] = ...), slice assignment (sliceable[start:end] = ...) and propably more are all method calls as well! And therefore you don't need global to change a global's members or call it methods (even when they mutate the object).


No, you can specify the list as a keyword argument to your function.

alist = []
def fn(alist=alist):
    alist.append(1)
fn()
print alist    # [1]

I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:

In file foomodule.py:

alist = []

In file barmodule.py:

import foomodule
def fn():
    foomodule.alist.append(1)
print foomodule.alist    # [1]

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to global-variables

What is the best way to declare global variable in Vue.js? How do I turn off the mysql password validation? How to declare Global Variables in Excel VBA to be visible across the Workbook How to create a global variable? global variable for all controller and views How to define global variable in Google Apps Script How to modify a global variable within a function in bash? Using a global variable with a thread Is it possible to use global variables in Rust? How to access global js variable in AngularJS directive