0

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?

1
  • 1
    What do you want last to reference when the list is empty?
    – Keith
    Commented Oct 31, 2012 at 2:58

2 Answers 2

8

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.

3
  • Wouldn't last = x[-1] if x[-1] else None be better?
    – John
    Commented Oct 31, 2012 at 3:01
  • 5
    @johnthexiii No, that would suffer from the same problem as just using last = x[-1]. The if x is designed to make sure x has at least one element in it, because an empty list is considered logically false.
    – Amber
    Commented Oct 31, 2012 at 3:03
  • @johnthexiii, You could check for if x[-1:], but I ythink if x is clearer anyway Commented Oct 31, 2012 at 3:11
3

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.