I'm doing the Python Crash Course and I got to this exercise, and I was wondering why the pop method is removing two list of my guest.
guest = ['aaron', 'john', 'pedro', 'kevin', 'mark', 'brad']
print(guest)
guest.pop()
print(f"{guest.pop()}")
print(guest)
Output:
['aaron', 'john', 'pedro', 'kevin', 'mark', 'brad']
mark
['aaron', 'john', 'pedro', 'kevin']
I tried assigning it with variable now it works. How is it different from the first though?
guest = ['aaron', 'john', 'pedro', 'kevin', 'mark', 'brad']
print(guest)
guest_1 = guest.pop()
print(f"{guest_1}")
print(guest)
Output:
['aaron', 'john', 'pedro', 'kevin', 'mark', 'brad']
brad
['aaron', 'john', 'pedro', 'kevin', 'mark']
guest.pop()
removes an element from the list each time it is called.
In your first code excerpt, the first call removes brad
, and since you don't assign it to a variable, it is effectively lost. You then call pop()
a second time, removing mark
, but this time you have wrapped the call in a print statement, so mark
is returned to the f-string and printed to the console.
In your second example, you only make one call to pop()
, store the result brad
in a variable, then print that variable.