Title: Variables changing values on their own
Type: behavior Stage: resolved
Components: Versions: Python 3.7
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List:, mark.dickinson, terry.reedy
Priority: normal Keywords:

Created on 2019-12-22 11:45 by, last changed 2019-12-22 22:38 by terry.reedy. This issue is now closed.

Messages (3)
msg358790 - (view) Author: Leonardo ( Date: 2019-12-22 11:45
in this code the variable o changes on its own:

x=[[-1, 7, 3], [12, 2, -13], [14, 18, -8], [17, 4, -4]]
x1=[[-8, -10, 0], [5, 5, 10], [2, -7, 3], [9, -8, -3]]
while k:
    for i in range(len(x)):
        for n in range(len(x)):
            if i!=n:
                for g in range(3):
                    if x[i][g]>x[n][g]:
                    if x[i][g]<x[n][g]:
    for i in range(len(x)):
        for n in range(3):
    for i in range(len(z)):
        if z[i]==x and d[i]==y:

A similar error happens when I try to append x values to a list, the list is filled with the same x value (the last one that has been appended) the number of times a x value had been appended in general.

For example:

if I had a values of x at the end of the while loop as 1, 2 and 3 and I appended them to a list the list would be [3, 3, 3] instead of [1, 2, 3]. If i wrote the list out each time a new x value is appended it would write it [1] first, then [2, 2] and then [3, 3, 3] at the end. 

I am really sorry for wasting time if this is just me being really dumb and messing something up.
msg358791 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2019-12-22 12:11
This isn't a bug. After this line in your code:

   o = x

both o and x refer to the same list object. So any modification you make to that list through the name "x" (for example, x[i][n]+=y[i][n]) will be seen through the name "o" as well.

There's lots written elsewhere explaining Python's assignment semantics. I highly recommend this presentation by Ned Batchelder:

You can also ask further questions on the Python mailing list:

Closing here.
msg358799 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2019-12-22 22:38
Leonardo, even if this were a bug, it would be a mistake to ascribe it to IDLE.  The IDLE Shell is an alternative display window. IDLE sends your code to Python and displays values computed by Python and output by print statements.  I second Mark's suggestion to first ask questions on python-list or other forums (at least until one has substantial experience with Python).
Date User Action Args
2019-12-22 22:38:37terry.reedysetassignee: terry.reedy ->
messages: + msg358799
components: - IDLE
2019-12-22 12:11:01mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg358791

resolution: not a bug
stage: resolved
2019-12-22 11:45:39leonardo.simunovic@gmail.comcreate