global list in python

To create a global list in Python, you can declare the list outside of any function or class, making it accessible to all parts of your code. Here's an example:

main.py
global_list = ["apple", "banana", "cherry"]

def add_item_to_list(item):
    global global_list
    global_list.append(item)

add_item_to_list("orange")
print(global_list)
172 chars
9 lines

In the example above, global_list is defined outside of any function, making it a global variable. The add_item_to_list function updates the global list by appending a new item. Be sure to use the global keyword inside any function that needs to access or modify the global list.

related categories

gistlibby LogSnag