Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why pop method removes two list at the same time?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading