Why does a = [123, 'First Item', 456] a.pop() print(a) show the ouput of [123, 'First Item']

Question:

Current behavior:

Desired behavior

Repl link:

code snippet

Hey @e7williams welcome to the forums!

Is this a school assignment? If so we cannot give you the answer but we can guide you in the right direction.

3 Likes

Also, if you provided the language this was in, that would help a lot.

2 Likes

It is probably python or some python-based language, or else they would use stdout or printf or echo etc

however from my experience of python (I barely use pop lol) this shouldn’t happen hmmmmm

2 Likes

@e7williams I believe .pop() automatically removes the last item of the list unless you input an index. If you wanted to remove the 123 (index of 0) .pop(0) will remove the “first item” in the list, lists start at index 0 and count up from there, so [123, ‘First Item’, 456] 123 is index 0, ’First Item’ is index 1, 456 is index 2.

4 Likes

As said in my post I believe it removes the last item in the list unless you specify otherwise

3 Likes
>>> a = [123, 'First Item', 456]
>>> a.pop()
456
>>> print(a)
[123, 'First Item']

(Assuming python code)
First, a is declared as a list of 3 elements.
Now, the pop method of list has the following behavior:

  • An index can be passed in as an argument. If no index is passed in, the index defaults to -1
  • The element at that index is removed from that list. (Also, the element is the return value.) It is an inplace operation, meaning the original list is mutated (no new list is created).

Remember that my_list[-1] gives the last element, as negative indices basically just go from the end to the start. So, the pop method removes the last (rightmost) element when no arguments are given. (The first element has index 0.)

In your code, the last element of a: 456, is removed and returned. (In the code, the return value is not used.) Then you print out a and see that 456 has been removed.

4 Likes

oh yeah my bad, I misunderstanded a.pop() to a = a.pop() and thought it should be and just be 456

yes a.pop() removes the last item by default unless specifying the index

3 Likes

To answer your question, if you don’t specify the index to pop, it will pop the last item of the list.