pythonのmapでAttributeError: 'map' object has no attribute 'xxxx'


はるか
AttributeError: ‘map’ object has no attribute ‘xxxx’。「map object」だと!
1. 問題のコード
def my_function(a):
return a**2
m = map(my_function, [1, 2, 3])
m.append(4)
print(m)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[20], line 4
2 return a**2
3 m = map(my_function, [1, 2, 3])
----> 4 m.append(4)
5 print(m)
AttributeError: 'map' object has no attribute 'append'
今回のPythonコードは二乗をリストに適用するためにmap関数を使用しましたが、AttributeError: ‘map’ object has no attribute ‘append’
エラーが出てしまいました。このエラーを解消しましょう。

はるか
おっ。AttributeErrorエラーが出た。

ふゅか
あーなるほど。mapのまま使用していることに問題あるみたいね。
1.1. 欲しい出力結果
2乗した値に4を追加したリストである出力結果を目標に修正する。
[1, 4, 9, 4]
1.2. 検証環境
Python 3.9.18
Windows11
Jupyter Lab 3.6.3
Windows11
Jupyter Lab 3.6.3
2. エラーの概要
map
オブジェクトに append
メソッドが存在しないために発生するエラーです。map
オブジェクトはイテレータであり、リストのように要素を追加するための append
メソッドを持っていません。
3. エラーの修正
def my_function(a):
return a**2
m = map(my_function, [1, 2, 3])
m.append(4)
print(m)
このコードでは、m
に対して append
メソッドを呼び出そうとしていますが、map
オブジェクトはこのメソッドを持っていないため、エラーが発生します。よって、map
オブジェクトをリストに変換してから要素を追加するようにコードを変更します。
def my_function(a):
return a**2
m = map(my_function, [1, 2, 3])
m_list = list(m)
m_list.append(4)
print(m_list)
3.1. コードの説明
my_function
という関数を定義しています。この関数は入力の数値を二乗します。map
関数を使って、リスト[1, 2, 3]
の各要素にmy_function
を適用して、それぞの要素を2乗しています。これによりmap
オブジェクトm
が生成されます。map
オブジェクトm
をlist()
関数を使ってリストm_listに変換します。- m_listに4を追加して、m_lsitを出力する。
4. 関連した記事
- pythonの関数について
- pythonのmap関数の使い方
- pythonのmap関数でTypeError: ‘xxx’ object is not iterable
- pythonのmapでTypeError: xxxx() missing 1 required positional argument: ‘b’
check
Pythonの基本から応用まで、幅広くカバーする記事を公開中です。学習のポイントや実践的なコード例を通じて、Pythonの魅力と実用性を深く理解することができます。ぜひ、こちらの記事で気になる記事を見つけてください!
PR