Python Forum
How to change global variable in function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to change global variable in function?
#5
that would be the better approach.
However you should know that list is a mutable type, and you can change the list elements inside the function without using global
my_list = [1, 2]
def change_list():
    my_list[0] = 3
    my_list[1] = 4

change_list()
print(my_list)

def change_list1(some_list):
    some_list[0] = 10
    some_list[1] = 11

change_list1(my_list)
print(my_list)

def change_list2():
    return [5, 6]

my_list = change_list2()
print(my_list)
Output:
[3, 4] [10, 11] [5, 6]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: How to change global variable in function? - by buran - Nov-10-2018, 07:07 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with writing monitored data to mysql upon change of one particular variable donottrackmymetadata 3 306 Apr-18-2024, 09:55 PM
Last Post: deanhystad
  Variable for the value element in the index function?? Learner1 8 671 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 602 Nov-23-2023, 02:53 PM
Last Post: rob101
  It's saying my global variable is a local variable Radical 5 1,186 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Printing the variable from defined function jws 7 1,336 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 954 Aug-07-2023, 05:58 PM
Last Post: Karp
  Retrieve variable from function labgoggles 2 1,056 Jul-01-2022, 07:23 PM
Last Post: labgoggles
  Cant transfer a variable onto another function KEIKAS 5 1,906 Feb-09-2022, 10:17 PM
Last Post: deanhystad
  Function global not readable by 'main' fmr300 1 1,356 Jan-16-2022, 01:18 AM
Last Post: deanhystad
  write new function or change the old one to work "smartter? korenron 3 1,990 Aug-09-2021, 10:36 AM
Last Post: jamesaarr

Forum Jump:

User Panel Messages

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