简体   繁体   中英

How to make the first element of the list unchange in python?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM