0

I've got the list x which is [10,20,30,40,50].
So the len of x is 5.
So the following makes sense:

>>> x=[10,20,30,40,50]
>>> print(list(range(len(x))))
[0, 1, 2, 3, 4]

I've put the above into a function and it seems to run.
What is the extra None that I get in the output?

def foo(aList):
    listLen = len(aList) 
    for x in list(range(listLen)):
        print(x)

x=[10,20,30,40,50]
print(foo(x))

EDIT
If I apply the above to a task of reversing a list it seems fine so the None doesn't cause a problem:

def foo(aList):
    newList = [] 
    listLen = len(aList) 
    for x in list(range(listLen)):
        newList.append(aList[listLen-(x+1)])
    return newList

x=[10,20,30,40,50]
print(foo(x))
whytheq
  • 34,466
  • 65
  • 172
  • 267

4 Answers4

2

print sends data to standard output (usually the terminal). print doesn't actually "return" anything from the function. To do that, you need the return keyword. Your function is printing the result inside the function and returning None (the default). The print statement outside the function then prints that return value which was None.

The fix is probably to return the list from your function instead of printing it's elements. Then you can print it outside the function. Something along the lines of:

def foo(aList):
    listLen = len(aList) 
    return list(range(listLen))

x=[10,20,30,40,50]
print(foo(x))
mgilson
  • 300,191
  • 65
  • 633
  • 696
2
print(foo(x))

This prints the return value of your foo() function. However foo() does not return anything, which implicitly means its return value is None. so you end up printing "None"

Perhaps you'd just want this:

def foo(aList):
    listLen = len(aList) 
    return list(range(listLen)):

x=[10,20,30,40,50]
print(foo(x))
nos
  • 223,662
  • 58
  • 417
  • 506
2

You print the return value from foo, and a function without an explicit return statement will return None.

Morten Zilmer
  • 15,586
  • 3
  • 30
  • 49
1
print(foo(x))

That prints what your function returns. You function prints the list and returns nothing.

Therefore the list being printed is the one your function prints. The print function prints None.

This function should do what you want.

def foo(aList):
    newList = [] 
    listLen = len(aList) 
    return range(listLen)

then

x=[10,20,30,40,50]
print foo(x)

Your function will return the list and the print statement will print it.


Another way to do it will be just calling the function without print.

def foo(aList):
    listLen = len(aList) 
    for x in list(range(listLen)):
        print(x)

x=[10,20,30,40,50]
foo(x)
shshank
  • 2,571
  • 1
  • 18
  • 27
  • 1
    Here you just return the first value from the list you created -- the rest of the values just disappear into the void of pythons garbage collector. I doubt that's what OP wants ;-) – mgilson Oct 10 '13 at 07:57
  • Aah! The Garbage collector, evil dark blackhole. I put in a gravity neutralizer. The list values are safe now. :D – shshank Oct 10 '13 at 08:05