Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm sure there's a simpler way of doing this that's just not occurring to me.

I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works:

my_list = get_list() 

if len(my_list) > 0: return my_list[0] 

return None

It seems to me that there should be a simple one-line idiom for doing this, but for the life of me, I can't think of it. Is there?

1 Answer

0 votes
by (106k points)

The best way is to use the below-mentioned code:-

a = get_list() 

return a[0] if a else None

You could also do it in one line, but it's much harder for the programmer to read:

return (get_list()[:1] or [None])[0]

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...