Orders and Lists

17 views
Skip to first unread message

Bennett Weaver

unread,
Nov 14, 2017, 4:47:59 PM11/14/17
to Glowscript Users
I am guessing that I am missing something, and I have a work around, but please clue me in as to what I am missing. 

In the following code snippet I generate a list a. From that I generate a list b. Reversing the list b also reverses the list a. Are things a bit different with variable assignments when using lists in python different than the other programming languages with which I have experience? TIA.

GlowScript 2.6 VPython
a = [0,1,2,3,4,5,6,7,8,9]
print("a", a) # prints "a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" as expected
b=a
print("a", a, "b", b) # prints "a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" as expected
b.reverse()
print("a", a, "b", b) # prints "a [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] b [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
#                            not the "a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]" that I had expected

Bruce Sherwood

unread,
Nov 14, 2017, 5:03:56 PM11/14/17
to Glowscript Users
Actually, this is indeed how Python works. If "a" is a "mutable" object such as a list, that is, an object that contains elements that can be modified without changing the other elements, then the statement "b = a" simply means that the object can be referred to either by the name "a" or by the name "b". There are now two names for the same object.

In true Python a list is mutable but a tuple such as (1,2,3) is not mutable, so that if "a" is a tuple then "b = a" creates what is effectively a different object: there are two objects and two names.

However, in GlowScript VPython there is no difference between a tuple made with parens and a list made with brackets; a tuple is treated exactly the same as a list. This is one of the differences between true Python and the RapydScript-NG Python-to-JavaScript transpiler used by GlowScript VPython. It is an essentially unavoidable consequence of the fact that RapydScript-NG is a relatively thin wrapper around the browser language, JavaScript. JavaScript does not have an object with the properties of a Python tuple.

Bruce

Bennett Weaver

unread,
Nov 16, 2017, 3:43:35 AM11/16/17
to Glowscript Users
Thanks for confirming what I had syspected. I was aware of mutable objects and how they could be affected as function parameters. 

I supose that being able to refer to the same items in a list might be useful as mentioned in another post,as a way to refer to individual objects in a compound generated from a list.

This is getting to be more fun all the time, especially trying to remember how to use the tools available as applied to whatever the current problem might be. Thanks, Bruce, for all your time and effort.
Reply all
Reply to author
Forward
0 new messages