PYTHON get the last item of a list even if empty

append, get, list, multithreading, python

Solution

Here's a way, although it looks odd:

`(list or [None])[-1]`

Problem

My Python script opens 2 `threading.Threads()` with the following functions : - `Stuff()` : function appending stuff to a `list` (global var) if stuff happens in a big loop. - `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 ?

Original source