How to get first element of list or `None` when list is empty?

Question:

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?

Asked By: BabaIsMe

||

Answers:

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
Answered By: Mouse
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.