This question already has an answer here:
Im using Python 3.4, operating system is Windows. It looks simple, but confused me.
This is going to add all different numbers from list1 to list2:
list1=[1,1,2,2,3,4]
list2=[]
for x in list1:
if x not in list2:
list2.append(x)
print (list2)
Output:
>>>
[1, 2, 3, 4]
>>>
But these codes also working too:
list1=[1,1,2,2,3,4]
list2=[]
for x in list1:
if not x in list2: #Difference is here
list2.append(x)
print (list2)
Output:
>>>
[1, 2, 3, 4]
>>>
Isnt it very strange? I just cant understand how can it possible. if x not in.. make sense, but why if not x in.. is working ? not x means opposite of x ?
Aucun commentaire:
Enregistrer un commentaire