Home > Back-end >  inserted list changes even after being inserted
inserted list changes even after being inserted

Time:08-10

I wanted to create a list of lists

def func(m,n,l,t):
    a=[i for i in range(m)]
    b=[]
    b.append(a)

    a=swap(a)
    b.append(a)

    for i in b:
        print(i)

def swap(l):
    i,n=0,len(l)
    while(i<n):
        l[i],l[i 1]=l[i 1],l[i]
        i =2
    return l

i created list a as my basis and append each modification i want to in the b list. The problem is after i append the first list and modify it, the first one i inserted also changes the same as the second one i inserted.

the output of this code is this

[1, 0, 3, 2, 5, 4, 7, 6]
[1, 0, 3, 2, 5, 4, 7, 6]

what i want is when i performm the swap i dont want the first list to change

the output should look like this

[0, 1, 2, 3, 4, 5, 6, 7]
[1, 0, 3, 2, 5, 4, 7, 6]

if you could help, please thank you.

CodePudding user response:

In place of append() method, you can try out extend() method which does the same as of append. but extend() method is mainly used for iterate items, as of in your case. and also if you want to use only append, then take a copy of your variable first and append it, as you are changing in the first place, it is taking effect in the list too. So you can follow append into a list like, a.copy(). Hopes it helps Please try out and share the feedback. Thank you

CodePudding user response:

Their are multiple code error you have done, for example:
you don't have to iterate over range object in order to get list, you could just...

a = list(range(m))

and also You don't have to run a while loop in order to iterate over two steps you could...

for i in range(0, len(l), 2):

see range for reference

also you didn't use any of n, l, t parameters of the func function.

THE ANSWER
when you pass the a variable to the swap function you are actually passing the class Object itself, so the swap function can change the value of the a variable (list class).
All you need is passing a copy of the a variable not the variable itself

a = swap(a.copy())

FINAL CODE

def swap(l):
    for i in range(0, len(l), 2):
        l[i],l[i 1]=l[i 1],l[i]
    return l

def func(m):
    a = list(range(m))
    b = [a]
    a = swap(a.copy())
    b.append(a)
    for i in b:
        print(i)

func(8) # [0, 1, 2, 3, 4, 5, 6, 7], [1, 0, 3, 2, 5, 4, 7, 6]

CodePudding user response:

Thank you guys, it is working now

I just added the

a=swap(a.copy())

and i got what i want thank you again.

  • Related