1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】リストの中身がtruthyかどうかを判定する方法

Posted at

📝 使うリスト

l = [1, 0, [], (2, 3), 'AA', '', False, ''*3]

✅ True(truthy)な要素だけをカウント

new_l = [i for i in l if bool(i)]
print(new_l)  # → [1, (2, 3), 'AA']
print(f"Trueの数 : {len(new_l)}")  # → Trueの数 : 3

👀 解説

Pythonでは、次のような値は False(falsy)扱い になります:

  • 0
  • ''(空文字)
  • [](空リスト)
  • ()(空タプル)
  • False そのもの

つまり、bool(x)True になるものだけが「truthy」という風にいなります!


最短で書く

print(f"Trueの数 : {sum(bool(i) for i in l)}")

truthy、falshyの取り扱いは慣れなのでいっぱい練習しましょう!!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?