PYTHON get the last item of a list even if empty

Issue

My Python script opens 2 threading.Threads() with the following functions :

  1. Stuff() : function appending stuff to a list (global var) if stuff happens in a big loop.
  2. Monitor() : function displaying the last item added to the list every second with additional info.

The purpose of these 2 threads is that Stuff() contains a loop optimized to be very fast (~ 200 ms / iteration) so printing from inside would be pointless. Monitor()takes care of the output instead.

At the beginning, I set list = [], then start the threads. Inside Monitor() I get the last item of the list with list[-1] but if no stuff happend before, the list is still empty and the Monitor() raises an IndexError: list index out of range.

Is there a simple way (no try or if not list) to display None instead of an error if the list is empty ?

Solution

Here’s a way, although it looks odd:

(list or [None])[-1]

Answered By – Alex Hall

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published