Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python typeError: can't multiply sequence by non-int of type 'float'

Tags:

python

list

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]
like image 488
Mark Aisenberg Avatar asked Mar 13 '26 15:03

Mark Aisenberg


1 Answers

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.

like image 65
Bhargav Rao Avatar answered Mar 16 '26 04:03

Bhargav Rao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!