SihwanLee
SihwanLee

Reputation: 169

Pop() not return any value when inside a function?

I'm currently learning about the pop() function in Python and have a question.

>>> a = [1,2,3,4]
>>> a.pop(3) #or a.pop()
4
>>> print(a)
[1,2,3]

I get that the pop() function removes and returns the value of the element corresponding to the index. However, the following example is the reason why I'm confused:

>>> a = [1,2,3,4]
>>> def solution(array):
        array.pop()
        return array
>>> solution(a)
[1,2,3]

First, I get that the function that I've described returns [1,2,3]. However, why does it not return the pop() value? Shouldn't it return 4 since the pop() function inside the solution() has a pop() function which, in definition, returns the value of the popped element?? I thought this pop() function kind of acts like del and print function simultaneously.

Upvotes: 3

Views: 1778

Answers (2)

Darian Lopez Utra
Darian Lopez Utra

Reputation: 83

cause you are not catching what pop() returns, the element is never printed, just in the python shell, you are returning the array modified, not the value returned by pop().

Edit: Btw , you don't need to return the array, the original array is already modified.

Upvotes: 2

mhhabib
mhhabib

Reputation: 3121

When you call return array after array.pop() it will return the rest of the element expcept the pop. Because you are returning array not all the specific pop opereation. Return array.pop() instead of array

def solution(array):
    return array.pop()

Or another way you can store the pop element and then you can return the pop variable.

def solution(array):
    pop_op=array.pop()
    return pop_op

Upvotes: 5

Related Questions