Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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.

like image 464
SihwanLee Avatar asked Mar 19 '26 11:03

SihwanLee


1 Answers

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
like image 168
mhhabib Avatar answered Mar 20 '26 23:03

mhhabib