0

I have lists that are empty and filled in the data. I am trying to the store last element of the list into a variable. If there are elements in the list, it is working fine. However, when I pass in a empty [] list, I get error like: IndexError: list index out of range. Which syntax I should be using for []?

ids = [
    'abc123',
    'ab233',
    '23231ad',
    'a23r2d23'
    ]

ids = []
# I tried these for empty
final = [ids if [] else ids[-1]] #error
# final = [ids if ids == None else ids == ids[-1]] # error
# final = [ids if ids == [] else ids == ids[-1]] # gives [[]] instead of []
print(final)

Basically, if an empty list is in ids, I need it to give []. If there are elements, then give the last element, which is working.

2
  • What do you expect to happen for an empty list? Commented Nov 1, 2018 at 17:36
  • you want to check if ids Commented Nov 1, 2018 at 17:37

5 Answers 5

2

Here is one way to do this:

final = ids[-1] if ids else None

(Replace None with the value you'd like final to take when the list is empty.)

Sign up to request clarification or add additional context in comments.

Comments

1

you can check for a empty list by below expression.

data = []
if data:  #this returns False for empty list
    print("list is empty")
else:
    print("list has elements")

so what you can do is.

final = data[-1] if data else []
print(final)

Comments

0
final = ids[-1] if len(ids) > 0 else []

This will handle the immediate problem. Please work through class materials or tutorials a little more for individual techniques. For instance, your phrase ids if [] doesnt' do what you (currently) seem to think: it does not check ids against the empty list -- all it does is to see whether that empty list is "truthy", and an empty list evaluates to False.

Comments

0

You are getting the error because you wont be able to select the last item if the list is empty and it will rightfully throw an IndexError.

Try this example

ids = [[i for i in range(10)] for x in range(3)]
ids.append([])

last_if_not_empty = [i[-1] for i in ids if i]

Here you filter out the non-empty list by if i which is the condition to select not empty lists. From there you can pick out the last elements of the lists.

Comments

0
a = list[-1] if not len(list)==0 else 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.