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?

More than 1 year has passed since last update.

【Python】リストの空の要素を消す方法

Last updated at Posted at 2021-12-10

環境

  • Microsoft Windows 10.0.22000.318(21H2)
  • Python 3.8.12.final.0

方法

1. filter関数を使う

list(filter(None, LIST_NAME)) でリストの空の要素を削除できる。

実行例
list_a = [[1, 2], [], [3, 4]]
list_b = list(filter(None, list_a))
print(list_b)
# [[1, 2], [3, 4]]

2. 内包表記を使う

[x for x in LIST_NAME if x != ''] でリストの空の要素を削除できる。

実行例
list_a = [[1, 2], [], [3, 4]]
list_b = [x for x in list_a if x != '']
print(list_b)
# [[1, 2], [], [3, 4]]

参考

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?