0

I want to access a list which is field from different python function. Please refer below code for more details

abc = []
name = "apple,orange"
def foo(name):
   abc = name.split(',')
   print abc

foo(name)
print abc
print name

The output is as below.

['apple', 'orange']

[]

apple,orange

Since I am new to python can anybody explain me why the 7th line (print abc) doesn't give the result as ['apple', 'orange']?

If I need to have the filled list at the line 7 (['apple', 'orange']), what should I do ?

DavidG
  • 24,279
  • 14
  • 89
  • 82
ShaAk
  • 190
  • 1
  • 12
  • Because, outside your function, `abc` is still an empty list... – DavidG Apr 03 '18 at 13:58
  • thanks.. what should I do to have the filed list? – ShaAk Apr 03 '18 at 13:58
  • 6
    Possible duplicate of [Short Description of the Scoping Rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – DavidG Apr 03 '18 at 13:58
  • 1
    add the line `global abc` within your `foo()` function if you want it to modify the global abc variable – abigperson Apr 03 '18 at 13:59
  • 2
    Possible duplicate of [python; modifying list inside a function](https://stackoverflow.com/questions/22054698/python-modifying-list-inside-a-function) – TMarks Apr 03 '18 at 14:01
  • 2
    This will make your programs more difficult to understand. Why do you need to have it global? Just return the list and assign it to a new name if needed. – Peter Wood Apr 03 '18 at 14:08

3 Answers3

2
abc = []
name = "apple,orange"
def foo(name):
   global abc # do this
   abc = name.split(',')
   print abc

foo(name)
print abc
print name
Todd W
  • 398
  • 1
  • 6
2

While other answers suggest to use global abc, it is considered (in general) to be bad practice to use global variables. See why are global variables evil?

A better way would be to return the variable:

name = "apple,orange"
def foo(name):
   abc = name.split(',')
   return abc

abc = foo(name)
print abc
print name
DavidG
  • 24,279
  • 14
  • 89
  • 82
0

abc from function is not the same as abc from first line, because abc in def foo is a local variable, if you want to refer to abc declared above you have to use global abc.

Silviu
  • 79
  • 9