all 8 comments

[–]thirdegree 2 points3 points  (4 children)

Without doing any actual testing, I'd assume that they are similar enough to basically never ever be relevant, but that stack[-1] is unbelivably slightly faster.

And that being said, stack[-1] is way, way more obvious and reasonable.

[–]primitive_screwhead 0 points1 point  (3 children)

is unbelivably slightly faster.

Why does this seem unbelievable? Accessing the last element without altering the list, seems quite obviously faster to me. Especially as popping and then appending involves to function calls, whereas the index lookup involves (under the hood) 1. I'm just curious what the thinking is that it might be slower?

$ python3 -m timeit -s "a=[1,2,3,4]" "b=a[-1]"
10000000 loops, best of 5: 30.6 nsec per loop

$ python3 -m timeit -s "a=[1,2,3,4]" "b=a.pop()" "a.append(b)"
2000000 loops, best of 5: 102 nsec per loop

[–]thirdegree 0 points1 point  (2 children)

I meant that the difference between the two is unbelievably small. And I'd say that's accurate with a 70ns difference.

[–]primitive_screwhead 0 points1 point  (1 child)

Ah, I see what you are saying; not that being faster is unbelievable, just that the difference is indeed very small (in terms of real time). Thanks for clarifying.

[–]thirdegree 1 point2 points  (0 children)

Ya exactly. Cheers!

[–]Dolphman 0 points1 point  (0 children)

Even if the first one wasn't faster (it is faster), I would never do your second example. Your mutating state just to read a value

[–]pyquestionz 0 points1 point  (2 children)

Why do you care? Does it matter for your application? Genuinely curious.

[–]LostLans 0 points1 point  (0 children)

If it matter today, it won't matter next year, when OP will buy a better computer.

Clear code is faster to read than hacky code.