0
2

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の便利な組み込み関数10選と活用例

Posted at

はじめに

Pythonには多くの便利な「組み込み関数」が標準で用意されています。これらを活用することで、コードの可読性や生産性が大きく向上します。本記事では、初心者から中級者まで役立つ「おすすめ組み込み関数10選」とその活用例を紹介します。


1. len()

リストや文字列などの要素数を取得します。

lst = [1, 2, 3]
print(len(lst))  # 3

2. enumerate()

ループ時にインデックスと要素を同時に取得できます。

for i, v in enumerate(['a', 'b', 'c']):
    print(i, v)

3. zip()

複数のリストを同時にループできます。

names = ['Alice', 'Bob']
ages = [24, 19]
for name, age in zip(names, ages):
    print(name, age)

4. map()

関数をリストの各要素に適用します。

nums = [1, 2, 3]
squared = list(map(lambda x: x**2, nums))
print(squared)

5. filter()

条件を満たす要素だけを抽出します。

nums = [1, 2, 3, 4]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)

6. sorted()

リストなどをソートします。

nums = [3, 1, 2]
print(sorted(nums))

7. any() / all()

条件を満たす要素が「1つでもある」「すべて満たす」か判定します。

nums = [1, 2, 3]
print(any(x > 2 for x in nums))  # True
print(all(x > 0 for x in nums))  # True

8. range()

指定した範囲の連番を生成します。

for i in range(5):
    print(i)

9. sum()

合計値を計算します。

nums = [1, 2, 3]
print(sum(nums))

10. set()

重複を除去した集合を作成します。

nums = [1, 2, 2, 3]
print(set(nums))

おわりに

組み込み関数を使いこなすことで、Pythonのコードはよりシンプルかつ強力になります。ぜひ日々の開発で活用してみてください!

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?