Home > front end >  How to get first element of list or `None` when list is empty?
How to get first element of list or `None` when list is empty?

Time:07-30

I can do it like this but there has to be better way:

arr = []
if len(arr) > 0:
    first_or_None = arr[0]
else:
    first_or_None = None

If I just do arr[0] I get IndexError. Is there something where I can give default argument?

CodePudding user response:

I think the example you give is absolutely fine - it is very readable and would not suffer performance issues.

You could use the ternary operator python equivalent, if you really want it to be shorter code:

last_or_none = arr[0] if len(arr) > 0 else None
  • Related