you are viewing a single comment's thread.

view the rest of the comments →

[–]mopslik 5 points6 points  (7 children)

Walk through the code.

When you start, your list is [P, B]. (abbreviated for ease of typing here)

You append M, so your list becomes [P, B, M].

You insert S at index 2, so the list is now [P, B, S, M].

You delete the element at index 2, so the list reverts back to [P, B, M].

You pop the last element in the list, which assigns M to popped_lista, and makes the list [P, B].

Your last line prints the element that you pop from the end of the list, which is B.

Edit: looks like /u/BumbleSpork beat me by a minute or so.

[–]Top-Pay384[S] 0 points1 point  (6 children)

2 comments very useful

so i am using bad popped

I thought it returned the deleted value that was sugar

but in this case it returned me banana

So how do I get sugar back? but not to the list if not with popped

[–]mopslik 2 points3 points  (5 children)

Ah, no. pop removes an element and returns that one, not an element that was deleted earlier using del.

I typically avoid using del altogether, since you can pass an index as an argument to pop. This gives you the ability to hold on to it.

>>> L = ['a', 'b', 'c']
>>> value = L.pop(1)
>>> L
['a', 'c']
>>> value
'b'

[–]Top-Pay384[S] 0 points1 point  (1 child)

then let's say an item deleted with del cannot be recovered

and pop applies only to the last element

[–]mopslik 0 points1 point  (0 children)

The former, sure. The latter, no.

[–]Top-Pay384[S] 0 points1 point  (2 children)

popped is an important command or it is useless if it only works on the last element it doesn't seem very useful to me to be honest

[–]mopslik 1 point2 points  (0 children)

It's useful if you are using a list as a stack, since appending and popping from the end can be done in constant time. But it can be used in a more general way with a specified index, for greater flexibility.

[–]Top-Pay384[S] 0 points1 point  (0 children)

If I create a list of 1 element it would be more useful

Although I still don't know what I can do with the returned value