Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the shortcode in Python like this:

a = [1, 2, 3]

b = a

b[0] = 100

print(a)

But I am getting the below result:

Output: [100, 2, 3]

How do I fix it?

1 Answer

0 votes
by (36.8k points)

In your example, both 'b' and 'a' are referring to an object. You should make a separate copy if you wish to change each of them independently. To solve it you have different ways: 

Option 1:

def Cloning(li1): 

    li_copy = li1[:] 

    return li_copy 

a = [1, 2, 3,] 

b = Cloning(a) 

b[0] = 100

print("Original List:", a) 

print("After Cloning:", b) 

2:

# Using the in-built function extend() 

def Cloning(li1): 

    li_copy = [] 

    li_copy.extend(li1) 

    return li_copy 

# Driver Code 

a = [1, 2, 3] 

b = Cloning(li1) 

b[0] = 100

print("Original List:", a) 

print("After Cloning:", b)

Option 3:

# Using the in-built function list() 

def Cloning(li1): 

    li_copy = list(li1) 

    return li_copy 

# Driver Code 

a = [1, 2, 3] 

b = Cloning(li1) 

b[0] = 100

print("Original List:", a) 

print("After Cloning:", b)

Option 4:

# Using list comprehension 

def Cloning(li1): 

    li_copy = [i for i in li1] 

    return li_copy 

  

# Driver Code 

    a = [1, 2, 3] 

    b = Cloning(li1) 

    b[0] = 100

    

    print("Original List:", a) 

    print("After Cloning:", b)

Option 5:

# Using append() 

def Cloning(li1): 

    li_copy =[] 

    for item in li1: li_copy.append(item) 

    return li_copy 

  

# Driver Code 

        a = [1, 2, 3] 

        b = Cloning(li1) 

        b[0] = 100

        

        print("Original List:", a) 

        print("After Cloning:", b)

Option 6:

# Using bilt-in method copy() 

def Cloning(li1): 

    li_copy =[] 

    li_copy = li1.copy() 

    return li_copy 

  

# Driver Code 

       a = [1, 2, 3] 

            b = Cloning(li1) 

            b[0] = 100

            

            print("Original List:", a) 

            print("After Cloning:", b)

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...