0
def pop(n):
    result,counter = 0,0
    while counter<=n:
        result=(2**counter)
        counter=counter+1
    return result

example:
>>>pop(4)
16

How do i return all the results? like:

1
2
4
8
16
5
  • pop is a built in function, you should avoid using it's name for your own function Commented Jan 30, 2014 at 10:21
  • @Kraay89: no, it isn't. Commented Jan 30, 2014 at 11:32
  • mylist = [1,2,3,4], mylist.pop() will work? What are you getting at? Am I using the wrong words? cause it is a valid python function... :S Commented Jan 30, 2014 at 11:58
  • 1
    @Kraay89, pop is not a "builtin" function. it is a method to the list class, but defining your own pop function will not shadow that, and so is not a problem. Commented Feb 3, 2014 at 20:27
  • I'm a bit ashamed right now, thanks for the explanation Commented Feb 6, 2014 at 17:45

2 Answers 2

4

You can store the result in an list:

def pop(n):
    result,counter = [],0
    while counter<=n:
        result.append(2**counter)
        counter=counter+1
    return result

Now the result will be a list of all powers.

Alternatively, you can create a generator to yield multiple results

def pop(n):
    result,counter = 0,0
    while counter<=n:
        yield 2**counter
        counter=counter+1

Now if you do a list(pop(4)), then you will get a list of all results

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

1 Comment

You probably meant yield instead of yeild :)
1

The pythonic way would be something like this:

def pop(n): return [2**x for x in range(n)]

1 Comment

More information on list comprehensions here: docs.python.org/2/tutorial/…. Your example is right there...

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.