[Tutor] returning values from function.
alan.gauld at btinternet.com
Mon Mar 23 20:17:22 CET 2009
"Bala subramanian" <bala.biophysics at gmail.com> wrote
> I wrote the following code to create two different list. One containing
> points of all clusters and another containing list of individual cluster
> data points. The script is as follows.
> data= # list of all data points
> all=[  for value in range(int(argv)) ] # Creating an empty list of
> def cluster(infile=argv,n=int(argv)):
> for index, line in enumerate(infile):
> if line.startswith('#Consensus'):
> data.extend(line) # data now should contain data points
> for value in range(n):
> for index, line in enumerate(data):
> if data[index] == str(value):
> #return data, all ( I even tried by un commenting the return
Here you define a function.
But you never call it...
> print all
> print data
So these have the same values that you initialised them to.
> The final print statement returns a empty list ie all and data. I have
> following queries
> i) Why the print statement returns empty lists
Because you never call the function.
> ii) Is return really required here, if i understand the namespace well,
> function cluster actually modifies the global variables data and all.
You are correct it modifuies the global value. But that is bad practice
and willl limit the reusability of the function. Indeed you will only ever
be able to use it on one data set at a time.
It would be much better to either pass in a refernce to a list or even
better initialise the list inside the function and return the populated
> iii) I even tried by using a return statement but still the script
> empty list.
Until you call it the return value has no effect.
> iv) Is there any fancy or better of way of doing this python.
There are probably several ways to improve the code (for example
you use enumerate in the first loop but never use index...), but I'd
just try to get it working first!
Author of the Learn to Program web site
More information about the Tutor