Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Unsupported type(s) : range and range

I'm getting this strange error trying to run a script, the code appears to be correct but it seems python (3) didn't liked this part:

        def function(x):
                  if integer:
                    return int(x)
                else:
                    return x

            non_nil = randrange(21)
            d = dict([(randrange(101), Racional(coeff(randrange(-20,20)),
                                    coeff(choice(range(-30,0)+\
                                                 range(1,30)))))
                     for k in range(non_nil)])

And i get the following error:

for k in range(non_nil)]) unsupported operand type(s) for +: 'range' and 'range'

I already tried to put the last four lines in a single one but python returns the same error.

like image 741
Monk Avatar asked Nov 10 '12 00:11

Monk


2 Answers

This is because Python 3 range does not return a list, unlike Python 2. This code was written for Python 2.

This code should be changed:

range(-30,0) + range(1,30)

It should be changed to:

[*range(-30,0), *range(1,30)]

Prior to Python 3.5 (2015, PEP 448 - Additional Unpacking Generalizations), you cannot use * inside lists, and must write it this way instead (or you may prefer this):

list(range(-30,0)) + list(range(1,30))
like image 103
Dietrich Epp Avatar answered Sep 19 '22 13:09

Dietrich Epp


As others have pointed out the problem is that in Python 3, range() returns an iterator not a list like it does in Python 2.

Here' one workaround: Add something like the following function:

def non_zero_range(lower, upper):
    ret = list(range(lower, upper))
    ret.remove(0)
    return ret

and then change the second Racional() call argument from:

coeff(choice(range(-30,0)+range(1,30)))

to simply:

coeff(choice(non_zero_range(-30,30)))

You will have something that would work in both Python 2 and 3.

like image 42
martineau Avatar answered Sep 18 '22 13:09

martineau