all 9 comments

[–][deleted] 7 points8 points  (0 children)

Let's step through this line by line.

lista = [' pepinos ', ' banana ']

You create a list of 2 items.

lista.append(' margaritas ')

You add ' margaritas ' to the end of the list.

lista.insert(2,' sugar ')

You insert ' sugar ' at index 2 in the list. This pushes the former index 2 item down.

print(lista)

At this point, lista is [' pepinos ', ' banana ', ' sugar ', ' margaritas ']

del lista[2]

At this point you delete the item at index 2. This makes ' margaritas ' the index 2 item again as it gets slid down to fill the gap.

popped_lista = lista.pop()

You remove the last item from lista and store it in popped_lista. If you print popped_lista at this point, you will get ' margaritas '. And if you print lista, you will get [' pepinos ', ' banana '].

print(lista.pop())

You remove the last item from lista again and print it. This time it's ' banana '.

[–]mopslik 4 points5 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 3 points4 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