1
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とJavaScriptのmap関数の違い

Posted at

はじめに

両言語にmap関数が存在しますが、動作と使い方に重要な違いがあります。

主な違い

特徴 JavaScript Python
配列のメソッド 組み込み関数
戻り値 新しい配列 イテレータ(mapオブジェクト)
即座の実行 はい いいえ(遅延評価)
呼び出し方 array.map() map(function, iterable)

1. 構文の違い

JavaScript

// 配列のメソッドとして呼び出す
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

Python

# 組み込み関数として呼び出す(関数が第1引数、リストが第2引数)
numbers = [1, 2, 3, 4, 5]
doubled = map(lambda num: num * 2, numbers)
print(list(doubled))  # [2, 4, 6, 8, 10]

2. 戻り値の違い(重要!)

JavaScript - 即座に配列を返す

const result = [1, 2, 3].map(x => x * 2);
console.log(result);        // [2, 4, 6] - すぐに使える
console.log(typeof result); // "object" (配列)

Python - イテレータを返す(遅延評価)

result = map(lambda x: x * 2, [1, 2, 3])
print(result)        # <map object at 0x...> - まだ実行されていない
print(type(result))  # <class 'map'>

# リストに変換して初めて実行される
print(list(result))  # [2, 4, 6]

# 再度使おうとすると空になる(一度しか使えない)
print(list(result))  # []

3. 実用例での比較

JavaScriptでのエラーメッセージ生成(app.jsのコード)

const msg = error.details.map(detail => detail.message).join(',');
// すぐに配列が生成され、joinで結合できる

Pythonで同じことをする場合

# 方法1: リストに変換してからjoin
msg = ','.join(list(map(lambda detail: detail['message'], error_details)))

# 方法2: リスト内包表記(Pythonではこちらが一般的)
msg = ','.join([detail['message'] for detail in error_details])

4. メモリ効率

JavaScript

// 大きな配列でも即座にメモリに展開される
const huge = Array(1000000).fill(1);
const doubled = huge.map(x => x * 2); // すぐに200万個の要素がメモリに

Python

# イテレータなので必要な時だけ計算(メモリ効率が良い)
huge = [1] * 1000000
doubled = map(lambda x: x * 2, huge)  # メモリに展開されない

# 必要な分だけ取り出せる
first_10 = list(doubled)[:10]  # 最初の10個だけ計算される

5. 複数のイテラブルの処理

Python(複数のリストを同時処理可能)

list1 = [1, 2, 3]
list2 = [10, 20, 30]
result = map(lambda x, y: x + y, list1, list2)
print(list(result))  # [11, 22, 33]

JavaScript(同等の機能はない)

// mapでは1つの配列しか処理できない
const list1 = [1, 2, 3];
const list2 = [10, 20, 30];
const result = list1.map((x, i) => x + list2[i]);
console.log(result);  // [11, 22, 33]

Pythonでの一般的な代替手段

Pythonではmap()よりもリスト内包表記が好まれることが多いです:

# map()を使う場合
doubled = list(map(lambda x: x * 2, [1, 2, 3]))

# リスト内包表記(より Pythonic)
doubled = [x * 2 for x in [1, 2, 3]]

# 辞書から値を取り出す(app.jsの例に相当)
messages = [detail['message'] for detail in error_details]

まとめ

  • JavaScript: 配列メソッド、即座に新しい配列を返す、そのまま使いやすい
  • Python: 組み込み関数、イテレータを返す、メモリ効率が良い、リスト内包表記の方が一般的

JavaScriptのmap()は直感的で使いやすく、app.jsのようなコードでは非常に便利です。Pythonでは同等の処理にリスト内包表記を使うことが推奨されています。

1
2
1

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
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?