6

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?

2
  • 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. Commented Jul 30, 2022 at 14:02
  • not know why question with 1 answer closed, any way what i looking for to not repeat the same code generated list and get value or no value if empty list *[1] *[] Commented Apr 28, 2024 at 14:27

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

2 Comments

You could shorten len(arr) > 0 to just arr because an empty array is False and non-empty True.
Ah even better - and something I didn't know - thanks :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.