Python で先頭の要素があれば取得し、なければ None を返す方法
Published: 2022/10/29
リストに対して、もしそれが空でなければ先頭の要素を取得し、空であれば None を取得する方法について。
Python idiom to return first item or None
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: def main()...
stackoverflow.com

上記より、以下のようにすれば良い。
next(iter(リスト), None)
Tags: python
関連記事
Python における空オブジェクトを作成する方法
2022/11/6