TypeError with map with no len()

Peter Otten __peter__ at web.de
Mon Sep 25 13:02:49 EDT 2017


john polo wrote:

> Python List,
> 
> I am trying to make practice data for plotting purposes. I am using
> Python 3.6. The instructions I have are
> 
> import matplotlib.pyplot as plt
> import math
> import numpy as np
> t = np.arange(0, 2.5, 0.1)
> y1 = map(math.sin, math.pi*t)
> plt.plot(t,y1)
> 
> However, at this point, I get a TypeError that says
> 
> object of type 'map' has no len()
> 
> In [6]: t
> Out[6]:
> array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7, 0.8,  0.9,  1. ,
>  1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8, 1.9,  2. ,  2.1,
>  2.2,  2.3,  2.4])
> In [7]: y1
> Out[7]: <map at 0x6927128>
> In [8]: math.pi*t
> Out[8]:
> array([ 0.        ,  0.31415927,  0.62831853,  0.9424778 , 1.25663706,
>  1.57079633,  1.88495559,  2.19911486,  2.51327412, 2.82743339,
>  3.14159265,  3.45575192,  3.76991118,  4.08407045, 4.39822972,
>  4.71238898,  5.02654825,  5.34070751,  5.65486678, 5.96902604,
>  6.28318531,  6.59734457,  6.91150384,  7.2256631 , 7.53982237])
> 
> At the start of creating y1, it appears there is an array to iterate
> through for the math.sin function used in map(), but y1 doesn't appear
> to be saving any values. I expected y1 to hold a math.sin() output for
> each item in math.pi*t, but it appears to be empty. Am I
> misunderstanding map()? Is there something else I should be doing
> instead to populate y1?

map() is "lazy" in Python 3, i. e. it calculates the values when you iterate 
over it, not before:

>>> def noisy_square(x):
...     print("calculating {0} * {0}".format(x))
...     return x * x
... 
>>> squares = map(noisy_square, [1, 3, 2])
>>> for y in squares:
...     print(y)
... 
calculating 1 * 1
1
calculating 3 * 3
9
calculating 2 * 2
4

While you can convert y1 to a list with

y1 = list(y1)

the better approach is to use numpy:

y1 = np.sin(t * math.pi)

Now y1 is a numpy.array and can be fed to pyplot.plot() directly.




More information about the Python-list mailing list