Skip to content
Advertisement

More pythonic way of item_list[-1] != item_list[-2]?

I’m updating and then referring to the last item added to a list to determine an outcome, for example:

if item_list[-1] != item_list[-2]:
   outcome1

I don’t need to refer to any other list element, just item_list[-1] & [-2]. Is there a more pythonic way of doing this? This code is for on_message using websockets, and the item_list is being updated once per second or once per minute. Any advice would be appreciated by this novice coder!

Advertisement

Answer

You can use tricks like *rest, x, y = item_list and then compare, but I think your method is great.

Chasing a “more pythonic” method for something you already have a great method for, is sometimes unnecessary. I do however encourage and like your attempt at getting better. Keep it up!

And if your asking about efficiency – Your method is probably the best there is.


Per your pondering in the comments:

Just so you’ll understand how fast it is, which is in the order of nanosecods and same speed no matter the length, here is a benchmark:

> py -m timeit -s "a = list(range(10_000))" "a[-1]"
2000000 loops, best of 5: 73.3 nsec per loop

> py -m timeit -s "a = list(range(100_000))" "a[-1]"
5000000 loops, best of 5: 74.5 nsec per loop

> py -m timeit -s "a = list(range(1_000_000))" "a[-1]"
5000000 loops, best of 5: 69.6 nsec per loop

More than 10 billion lookups per second (on my old computer from 2009) is fast enough I think ;-)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement