2

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?

BabaIsMe
  • 33
  • 1
  • 5
  • 1
    You can use: `first_or_none = arr[0] if arr else None` (`if arr` is just a shortened way to write `if len(arr) > 0`). Indexing the first item needs index `0`. – ewz93 Jul 30 '22 at 14:02

1 Answers1

4

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
Mouse
  • 395
  • 1
  • 7