1

I need to print the elements of list, such that if an element is 100 or greater, it's followed by a newline, and if not, it's followed by a space.

This is what I have so far:

def function(list):
    if list == []:
        return None
    elif list[0] >= 100:
        print(list[0], function(list[1:]), end = '\n')
    else:
        print(list[0], function(list[1:]), end = '')
    return None

But when I try list = [2,3,103, 8, 10], Python prints:

10 None8 None103 None

3 None2 None

Any suggestions/help?

1
  • The problem is that you're printing the function call's returns as well. Put the recursive calls outside of the print statements. Commented Nov 30, 2013 at 21:09

3 Answers 3

1

You're on the right track. This is what you want:

def function(lst):
    if not lst:
        return
    elif lst[0] >= 100:
        print(lst[0], end='\n')
    else:
        print(lst[0], end=' ')
    function(lst[1:])

(I renamed list to lst because list is a builtin type that we don't want to overwrite).

Explanation: if we have the recursive call inside the print call, we print the return value of the function, which is always going to be None, as it never returns anything else. So we have to move it outside.

Also, the boolean value of an empty list is False, so we can replace lst == [] with not lst, as recommended by PEP 8.

Sign up to request clarification or add additional context in comments.

Comments

1

list is a reserved word.

myList = [2,3,103, 8, 10]
for i in myList:
   print(i, end = (i>=100) and '\n' or ' ')

2 Comments

print as a function strongly suggests Python 3.x, so you can use "\n" if i >= 100 else " " instead of the dodgy and or thing.
True - I am more used to python 2.x
0

After your function exists it returns None, which is why your print statements have the "None" in them. Just move the recursive call outside of print

    elif list[0] >= 100:
        function(my_list[1:])
        print(my_list[0], end='\n')
    else:
        function(my_list[1:])
        print(my_list[0], end='')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.