Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
first_or_none = arr[0] if arr else None
if arr
if len(arr) > 0
0
*[1]
*[]
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
Add a comment
len(arr) > 0
arr
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
first_or_none = arr[0] if arr else None(if arris just a shortened way to writeif len(arr) > 0). Indexing the first item needs index0.*[1]*[]