Mark Aisenberg
Mark Aisenberg

Reputation: 123

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

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]

Upvotes: 2

Views: 10594

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52151

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.

Upvotes: 6

Jérôme
Jérôme

Reputation: 14714

You can't do element-wise operations on lists.

Using list comprehensions:

a = [0.0, 1.1, 2.2]
b = [2 * i for i in a]

Using numpy (faster for large lists):

import numpy as np

a = np.array([0.0, 1.1, 2.2])
b = a * 2.0

(then you get a numpy array, not a list)

Upvotes: 3

Related Questions