[Tutor] returning values from function.

Alan Gauld 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 
> data
> 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[2])) ]  # Creating an empty list of
> def cluster(infile=argv[1],n=int(argv[2])):
>        for index, line in enumerate(infile):
>            if line.startswith('#Consensus'):
>                line=line.split()
>                data.extend(line[2]) # data now should contain data points
>        for value in range(n):
>                for index, line in enumerate(data):
>                    if data[index] == str(value):
>                            zero=index+1
>                            all[value].append(zero)
>        #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 
> the
> 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, 
> the
> 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 
> returns
> 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!


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list