简体   繁体   中英

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?

这是一种方法,尽管看起来很奇怪:

(list or [None])[-1]

I find this more readable than @Alex's answer

lst = [1, 3, 2]
print None if not lst else lst[-1]

Edit: Though must admit, it is the first time I encountered that usage. Always thought those expressions returned bool type :)

You can use it also like this:

[1, 2, 3, 4][-1:] -> [4]
[][-1:]           -> []
[][-1:] or None   -> None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM