Say I have the list x = []. I need to keep track of the last element in that list. I could do this with the variable last = x[-1], but of course this gives an index error if x is empty. How can I account for this so that I don't get an error when x is empty?
2 Answers
You can use a conditional expression:
last = x[-1] if x else None
Put whatever you want in case of an empty list in place of None.
-
-
5@johnthexiii No, that would suffer from the same problem as just using
last = x[-1]
. Theif x
is designed to make surex
has at least one element in it, because an empty list is considered logically false.– AmberCommented Oct 31, 2012 at 3:03 -
@johnthexiii, You could check for
if x[-1:]
, but I ythinkif x
is clearer anyway Commented Oct 31, 2012 at 3:11
You could try x[-1:]
which returns a list containing either the last element, or an empty list if x
is the empty list. Of course, if you want to use that element for something, you'll still have to check to see whether it is present or not.
last
to reference when the list is empty?