Bùi Văn Thủ
Bùi Văn Thủ

Reputation: 393

copy list inside function python

I am getting frustrated with this code, I've read some articles, but it seems I wasn't figure it out:

class c:
def __init__(self):
    self.k = [9, 8]
def a(x):
    k = c()
    x = k.k

l = [1, 9]
a(l)

print l # expects [9, 8], got [1, 9]

update, I found a rather rogue way:

class c:
    def __init__(self):
        self.k = [9, 8]
def a(x):
    k = c()
    for i in reversed(x):
        x.remove(i)
    for i in k.k:
         x.append(i)


l = [1, 9]
a(l)

print l # output [9, 8]

Upvotes: 0

Views: 307

Answers (1)

dawg
dawg

Reputation: 103814

It is difficult for me to tell what you are trying to do. Let me make some assumption and point a few things out.

Your corrected code:

class C:     # by convention, Python classes are capitalized...
    def __init__(self):
        self.k = 10       
    def a(self, x):       # you need 'self' to refer to what instance
        x[1] = self.k

Now you can do what I think you are trying to do:

>>> c=C()          # you need an instance of that object
>>> li=[1,2]
>>> c.a(li)
>>> li
[1, 10]

The attribute k has the same scope as c, so if you want .k to be global make c global:

>>> c.k
10
>>> c.k=22
>>> c.k
22

Upvotes: 3

Related Questions