Aurélien Pierre Aurélien Pierre - 1 month ago 6
Python Question

PYTHON get the last item of a list even if empty

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 ?

Answer

Here's a way, although it looks odd:

(list or [None])[-1]