+ 1

Difference between list.clear() and list=[]

Why does the sample code below give different results when I replace templist=[] with templist.clear()? Aren't they supposed to be the same? https://code.sololearn.com/cHH0D7On2cF8/?ref=app

12th Apr 2018, 4:35 PM
Tamim Arafat
Tamim Arafat - avatar
4 Réponses
+ 4
Tamim Arafat list.clear() is more accurate and powerful than list=[] empty list. when you convert the list into empty list it change only it's own state but when you use clear it will also take effect on it's own state and other dependable list on it.e. g= x=[1,2,3] y=[] y.append(x) x.clear() print(x) #ouput=[] print(y) # output=[[]] this is due to because y depend on x and x is now clear so other dependable list will also become empty list list.clear is directly proportional to the append method.but in list=[] empty list it is opposite empty list method is inversely proportional to the append method.
13th Apr 2018, 2:20 AM
Maninder $ingh
Maninder $ingh - avatar
+ 1
clear use for make the list empty. and list= [] is also empty list.so y=[1,2] y.clear() print(y) #ouput=[] x=[] print(x==y) #ouput=True
12th Apr 2018, 5:35 PM
Maninder $ingh
Maninder $ingh - avatar
0
Maninder Singh I know that. My question was why does my code give different results if I use list.clear() instead of list=[]
12th Apr 2018, 5:38 PM
Tamim Arafat
Tamim Arafat - avatar
0
Maninder Singh Thanks for the answer :-)
13th Apr 2018, 9:06 AM
Tamim Arafat
Tamim Arafat - avatar