2

I want this program in python

m = [[1,0,0],
     [0,1,0],
     [0,0,1]]

n = [[1,2,3],
     [2,3,4],
     [2,4,1]]

def cofactor(s,j):
    p = m.copy()
    for i in range(0,len(p)):
        p[i].pop(s)
    p.pop(j)
    return p
cofact = cofactor(2,1)
print(cofact)
print(m)

To give me back this

[[1, 0], [0, 0]]
[[1,0,0],[0,1,0],[0,0,1]]

but instead is giving

  [[1, 0], [0, 0]]
[[1, 0], [0, 1], [0, 0]]

And I do not know what am i doing wrong. I need to understand and find my mistake. Thanks.

1 Answers1

0

From Python documentation, 3. Data models >>> 3.1. Objects, values and types

Some objects contain references to other objects; these are called containers. Examples of containers are tuples, lists and dictionaries. The references are part of a container’s value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.

Elements (lists and their respective elements) of m and p refer to same objects. If these objects are changed it reflects in both container objects. It can be easily verified.

After assingment of m add:

print(id(m[0]), id(m[0][0])) 

And after assignment of p inside function body:

print(id(p[0]), id(m[0][0]))

You will see that identities of these objects are same.

You should also check explanation in The Python Standard Library >>> 8. Data types >>> 8.10. copy - Shallow and deep copy operations

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

In order to avoid such problems in future I recommend checking out StackOverflow contributor Ned Batchelder very good explanation about names and values: Python Names and Values

Aivar Paalberg
  • 4,645
  • 4
  • 16
  • 17