I have this code
a = [0.0, 1.1, 2.2]
b = a * 2.0
and that is where I get the error
typeError: can't multiply sequence by non-int of type 'float'
what I want it to return is
b = [0.0, 2.2, 4.4]
The error is that you are multiplying a list, that is a and a float, that is 2.0.
Do this instead (a list comprehension)
b = [i*2.0 for i in a]
A small demo
>>> a = [0.0, 1.1, 2.2]
>>> b = [i*2.0 for i in a]
>>> b
[0.0, 2.2, 4.4]
Using map
map(lambda x:x*2.0 , a)
Here are the timeit results
bhargav@bhargav:~$ python -m timeit "a = [0.0, 1.1, 2.2]; b = [i*2.0 for i in a]"
1000000 loops, best of 3: 0.34 usec per loop
bhargav@bhargav:~$ python -m timeit "a = [0.0, 1.1, 2.2]; b = map(lambda x:x*2.0 , a)"
1000000 loops, best of 3: 0.686 usec per loop
bhargav@bhargav:~$ python -m timeit "import numpy; a = numpy.array([0.0, 1.1, 2.2]); b = a * 2.0"
10 loops, best of 3: 5.51 usec per loop
The list comprehension is the fastest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With