An Interview Question about changing/not changing values of the Original Data of List in Python
Hi everyone
For example given a list object :
list1 = [1,2,3,4,5]
You are expected to answer code output in below conditions
Condition-1
list2 = [list1]
list1[1] = 100
print(list2)
Condition-2
list3 = [10,20,30]
list3.append(list1)
list1[1] = 100
print(list3)
Condition-3
list4 = list1[:]
list1[1] = 100
print(list4)
Condition-4
list5 = list1.copy()
list1[1] = 100
print(list5)
Condition-5
list6 = list(list1)
list1[1] = 100
print(list6)
Condition-6
list7 = [item for item in list1]
list1[1] = 100
print(list7)
Condition-7
import copy
list8 = copy.deepcopy(list1)
list1[1] = 100
print(list8)
Explanation
In Python, lists are mutable, meaning they can be modified after creation. If you need to create a copy of a list to preserve the original data, you can clon or copy a list.
Condition-1 and Condition-2 explanation
After changing list1, list2 and list3 will change.
In Python, assigning the list from variable a
to variable b
causes both variables to reference the same list object and therefore share the data. Consequently, any change applied through one variable will impact the other.(Python doc)
#First list2 = [1, 2, 3, 4, 5]
#First list3 = [10, 20, 30, [1, 2, 3, 4, 5]]
#After changing list1, list2 = [[1, 100, 3, 4, 5]]
#After changing list1, list3 = [[1, 100, 3, 4, 5]]
[[1, 100, 3, 4, 5]]
[10, 20, 30, [1, 100, 3, 4, 5]]
Condition-3 explanation
list4 can not change.
The slicing operator ([:]) selects all elements from the list.A new list is created with the same elements, separate from the original.
#First list4 = [1, 2, 3, 4, 5]
#After changing list1, list4 = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Condition-4 explanation
list5 can not change.
The copy() method creates a new list with the same elements as the original.It is a shallow copy, meaning it copies the references of nested objects, not the objects themselves.
#First list5 = [1, 2, 3, 4, 5]
#After changing list1, list5 = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Condition-5 explanation
list6 can not change.
list() constructor takes an iterable (like a list) as input and creates a new list with the same elements.It creates a shallow copy of the list.
#First list6 = [1, 2, 3, 4, 5]
#After changing list1, list6 = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Condition-6 explanation
list7 can not change.
The list comprehension iterates through each element of the original list and adds it to the new list.
#First list7 = [1, 2, 3, 4, 5]
#After changing list1, list7 = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Condition-7 explanation
list8 can not change.
deepcopy() function recursively copies all objects inside the list.It ensures that changes to nested objects in the clone do not affect the original.
#First list8 = [1, 2, 3, 4, 5]
#After changing list1, list8 = [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
I hope, it was useful for you
Thanx for reading.