Pixel Pedals of Tomakomai

北海道苫小牧市出身の初老の日常

python3のmapはリストを返さない

cols_upper = map(str.upper, "a,B,c".split(","))
cols_lower = map(str.lower, cols_upper)

for c in cols_lower:
    print(c)

for c in cols_upper:
    print(c)

python2 だと動く。

A
B
C
a
b
c

python3だと動かない。

A
B
C

python3では戻り値がイテレータに変わっているため。

Return an iterator that applies function to every item of iterable, yielding the results.

Built-in Functions — Python 3.7.2 documentation

Apply function to every item of iterable and return a list of the results.

2. Built-in Functions — Python 2.7.15 documentation

list でラップすることで、今までの挙動と同じにできる。

mapfilter はリストに対する操作であるという印象が強いので、この仕様には面食らった。特に、イテレータはリストと違って内部に状態を持つミュータブルな値だということに、厳しみを感じる。

そんなわけで(?)、2019年もよろしくお願い致します。