Problems with Python range() as list

38 views
Skip to first unread message

Adam Thompson

unread,
Apr 30, 2017, 2:01:23 AM4/30/17
to Glowscript Users
Usually, in Python, two lists can be concatenated using the "+" operator or the extend() method.

The "+" operator works for standard lists in Glowscript VPython, but does not work for lists created using the range() method.

The following code fails:
for j in range(0,i) + range(i+1,N):
# Some code that uses (i,j) pairs
with the following error:
TypeError: range(...).+ is not a function 

Bruce Sherwood

unread,
Apr 30, 2017, 9:39:00 AM4/30/17
to Glowscript Users
I'll report this to the developer of RapydScript-NG. My guess is that we're out of luck on this one, because I think that range isn't a real list but essentially a "generator".

In this forum see the somewhat related issue discussed in the April 3 note titled "max(), min(), arange(), list".

Bruce Sherwood

unread,
May 1, 2017, 9:01:14 AM5/1/17
to Glowscript Users
In Python 2 range was an actual list (which meant that it could be very large in memory) but in Python 3 it is a generator (something that doles out the next value when asked for one), and in Python 3 the following code

a = range(3)
b = range(5)
c = a+b

gives this error:

TypeError: unsupported operand type(s) for +: 'range' and 'range'

So this isn't a bug, it's a feature, as RapydScript is closer to Python 3 than to Python 2.



Adam Thompson

unread,
May 1, 2017, 6:47:55 PM5/1/17
to Glowscript Users
Gotcha! (I also looked at the min,max post you mentioned earlier.)
So I should use list(range(...)) instead?
For example,
for j in list(range(0,i)) + list(range(i+1,N)):
# code for index pair (i,j)

I will have to try it when I get home.

Reply all
Reply to author
Forward
0 new messages