Yukii's Blog

  • Scraps
  • V2

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
block.opendns.com のリファラーについて調べたこと
DynamoDB の命名規則まわり

関連記事

Python における空オブジェクトを作成する方法

python

2022/11/6

AttributeError: module 'socketio' has no attribute 'Client' の対処方法

pythonsocketio

2019/11/20

Rubyist のための python 標準 logging モジュールの擬似コード

pythonloggingruby

2019/5/27

About

エンジニアです。 仕事では Xincere Residence を作っています。 このサイトは個人のブログであり、所属団体の意見等とは関係がありません。

Popular

  • Mac で mds_stores が重い問題に正しく対処する
  • "[vite]: Rollup failed to resolve import" の対応
  • Nginx の log_format を変更したけれども反映されずハマった話
  • RSA 暗号と中国剰余の定理による高速化についてのまとめ
  • useAsyncData とそれを実現する Nuxt 3 の非同期処理の機構

Feed

Tags

Archives

  • 2022(67)
    • 2022/11 (3)
    • 2022/10 (14)
    • 2022/9 (4)
    • 2022/8 (3)
    • 2022/7 (7)
    • 2022/6 (8)
    • 2022/5 (5)
    • 2022/4 (6)
    • 2022/3 (6)
    • 2022/2 (6)
    • 2022/1 (5)
  • 2021(36)
  • 2020(13)
  • 2019(19)
  • 2018(1)

© 2018-2022 Yukii