1

Here is my list,

a = [['a','b','c','d'],['e','f','g','h'],['i','j','k','l'],['m','n','o','p']]

and Here is my function,

def add(change,unchange):
    a = change
    b = unchange
    a[0].insert(a[0].index(a[0][2]),"high_range")
    a[0].insert(a[0].index(a[0][3]),"low_range")
    print(a)
    print(b)

When I try to execute this function,

add(a,a[0])

I'm getting this output,

[['a', 'b', 'high_range', 'low_range', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p']]
['a', 'b', 'high_range', 'low_range', 'c', 'd']

But my expected output is the following,

[['a', 'b', 'high_range', 'low_range', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p']]
['a', 'b', 'c', 'd']

How to make the first element of the list keep on same in the second variable ? Sorry I'm newbie.

sodmzs
  • 184
  • 1
  • 16

3 Answers3

1

Since a list is a mutable type, when you insert values into a this also gets reflected in b, since they are pointers to the same list. You can either print b before inserting values into the list, or make b a copy of unchange like this:

def add(change,unchange):
    a = change
    b = unchange[:]
    a[0].insert(2, "high_range")
    a[0].insert(3, "low_range")
    print(a)
    print(b)

Also, a[0].index(a[0][2]) is redundant, you already know that the index is 2.

alec
  • 5,799
  • 1
  • 7
  • 20
1

The main problem is in line:

add(a, a[0])

as you are mutating a inside the function a[0] will change as well as they point to the same thing. You need to design your program accordingly. You can refer to this answer. How to clone or copy a list?

depending upon your requirement you can do this.

  1. either suply a copy while calling a function.

add(a, a[0][:]) # or

  1. read @alec's answer.
Rahul
  • 10,830
  • 4
  • 53
  • 88
1

your function is perfect but execute this:

add(a,a[0][:])

this will make the second variable, namely a[0], a copy, which will be left unchanged.

Bolun Han
  • 36
  • 4