[[0,0,0]]*3 Not working in python console

Use this forum to talk about enhancements and fixes.

[[0,0,0]]*3 Not working in python console

Postby abottero » Tue Jan 29, 2019 6:48 pm

Hello all,

There is an annoying bug I wanted to highlight:

#coordinates = [[0,0,0]]*3 # Not working
coordinates = [[0,0,0],[0,0,0],[0,0,0]] # Working

for i in range(3):
coordinates[i][0] = i
coordinates[i][2] = 2*i

print(coordinates)

I am using Trelis 16.5

Thank you,

Have a good evening
abottero
 
Posts: 7
Joined: Mon Feb 23, 2015 3:06 am

Re: [[0,0,0]]*3 Not working in python console

Postby csimsoft Moderator » Wed Jan 30, 2019 1:06 pm

NOTE: Python indentations were lost in the forum post.

I tested this script in straight Python 2.7 and 3.3 and got this:

>>> coordinates = [[0,0,0]]*3
>>> for i in range(3):
coordinates[i][0] = i
coordinates[i][2] = 2*i

>>> print(coordinates)
[[2, 0, 4], [2, 0, 4], [2, 0, 4]]

Then, I moved the print function inside the For loop and see that the coordinate values are changing:

>>> coordinates = [[0,0,0]]*3
>>> for i in range(3):
coordinates[i][0] = i
coordinates[i][2] = 2*i
print(coordinates)

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 2], [1, 0, 2], [1, 0, 2]]
[[2, 0, 4], [2, 0, 4], [2, 0, 4]]
>>>

The script with the print function outside the loop is only printing the very last coordinate values from the third loop.

So, by using "coordinates = [[0,0,0]]*3" Python will print the coordinates three times on the same line. By using "coordinates = [[0,0,0],[0,0,0],[0,0,0]]", Python will print the coordinate value of each loop on the same line, like this:

>>> coordinates = [[0,0,0],[0,0,0],[0,0,0]]
>>> for i in range(3):
coordinates[i][0] = i
coordinates[i][2] = 2*i

>>> print(coordinates)
[[0, 0, 0], [1, 0, 2], [2, 0, 4]]
>>>
csimsoft
csimsoft Moderator
 
Posts: 294
Joined: Tue Feb 14, 2012 5:59 pm
Location: American Fork, UT

Re: [[0,0,0]]*3 Not working in python console

Postby abottero » Wed Jan 30, 2019 4:52 pm

Hello,

You are right, I am sorry.

This is due to a strange behaviour of python reported also there: https://stackoverflow.com/questions/127 ... t-of-lists

coordinates1 = [[0,0,0]]*3

and

coordinates2 = [[0,0,0],[0,0,0],[0,0,0]]

Although identical when printed does not behave the same way.

Thank you for your help
abottero
 
Posts: 7
Joined: Mon Feb 23, 2015 3:06 am


Return to Feature Requests and Fixes

Who is online

Users browsing this forum: No registered users and 1 guest

cron

Search / Mark

User Control Panel

Login

Who is online

In total there is 1 user online :: 0 registered, 0 hidden and 1 guest (based on users active over the past 5 minutes)
Most users ever online was 83 on Tue Nov 13, 2018 11:44 am

Users browsing this forum: No registered users and 1 guest