Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Why do we use pop(0) instead of pop()?

Why do we take the elements from the start of the list (https://teamtreehouse.com/library/objectoriented-python/hacknslash/game-planning), and don't use pop() method with no arguments? In this case, we would take items from the list from the end and speed would be always equal to O(1), and if you take elements from the beginning of the list, the performance will be O(n) because we have to move all elements of a list one step to the left. In this example, it will not affect speed, but if there is a huge list, remove items from start of list, not an optimal solution.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

Nice observation! You are correct in that the performance of pop(0) is significantly slower than pop() for large lists (above 10,000 elements). See timeit results below.

I believe Kenneth Love chose to pop from the front of the list as a straight-forward logical approach without trying to optimize for performance. Since the order of monsters in the list is arbitrary, popping from the back or the front isn't a requirement and either approach would work functionally.

Using timeit in the python REPL:

>>> import timeit
>>> stmt1 = "while foo: it = foo.pop();"
>>> stmt2 = "while foo: it = foo.pop(0);"
# Run on 1000 element list
>>> setup = "foo = list(range(1000))"
>>> timeit.timeit(stmt1, setup)
0.051728010177612305
>>> timeit.timeit(stmt2, setup)
0.05761384963989258
# Run on 10,000 element list
>>> setup = "foo = list(range(10000))"
>>> timeit.timeit(stmt1, setup)
0.05236983299255371
>>> timeit.timeit(stmt2, setup)
0.06780695915222168
# Run on 100,000 element list
>>> setup = "foo = list(range(100000))"
>>> timeit.timeit(stmt1, setup)
0.0552210807800293
>>> timeit.timeit(stmt2, setup)
1.3619050979614258
# Run on 1,000,000 element list
>>> setup = "foo = list(range(1000000))"
>>> timeit.timeit(stmt1, setup)
0.10635495185852051
>>> timeit.timeit(stmt2, setup)
226.78901600837708

Big thanks for your answer.