Reputation: 63
I am very new to programming and not good at English. plz understand even if I make mistakes. here is my question, I want to remove object is self form list. how can I get result as like first one I tried even though I switch to asd=ad_material_name2
what I tried is
ad_material_name=['a', 'b', 'c']
ad_material_name2=['a', 'b', 'c']
for aa in ad_material_name:
asd=['a', 'b', 'c']
asd.remove(aa)
print(asd)
it's result came out like this
['b', 'c']
['a', 'c']
['a', 'b']
so, I thought it worked. but, when I tried this
ad_material_name=['a', 'b', 'c']
ad_material_name2=['a', 'b', 'c']
for aa in ad_material_name:
asd=ad_material_name2
asd.remove(aa)
print(asd)
it came out like this.
['b', 'c']
['c']
[]
I thought from here it might be a problem of ad_material_name=['a', 'b', 'c']=ad_material_name2 and it some how effect result. so, I tried this.
ad_material_name=['a', 'b', 'c']
ad_material_name2=['a', 'b', 'c', 'b']
for aa in ad_material_name:
asd=ad_material_name2
asd.remove(aa)
print(asd)
but, it came out like this
['b', 'c', 'd']
['c', 'd']
['d']
how can I get result as like first one I tried even though I switch to asd=ad_material_name2
Upvotes: 0
Views: 98
Reputation: 1672
The problem with your second code is that Python lists are mutable; they can be changed. Assigning a variable to a list, and then changing the variable- changes the list as well.
e.g:
def make123(array):
array[2] = 3
array[1] = 2
array[0] = 1
e = [3, 5, 6]
make123(e)
print(e) # [1, 2, 3]
You might wanna use a tuple, then convert it to a list:
ad_material_name=['a', 'b', 'c']
ad_material_name2=('a', 'b', 'c')
for aa in ad_material_name:
asd=list(ad_material_name2)
asd.remove(aa)
print(asd)
"""
['b', 'c']
['a', 'c']
['a', 'b']
"""
Upvotes: 0
Reputation: 89527
You might use combinations function from itertools to achieve the same result.
from itertools import combinations
ad_material_name=['a', 'b', 'c']
for x, y in combinations(ad_material_name, r=2):
print([x, y])
or if you need to create ad_material_name2 variable and assign permutations to it, you can do following:
from itertools import combinations
ad_material_name=['a', 'b', 'c']
ad_material_name2 = [[*comb] for comb in combinations(ad_material_name, r=2)]
print(ad_material_name2)
# output
[['a', 'b'], ['a', 'c'], ['b', 'c']]
Upvotes: 2
Reputation: 262
modify
asd=ad_material_name2
to
asd=ad_material_name2.copy()
so that the "remove" opertion will not modify the list ad_material_name2 directly.
Upvotes: 2
Reputation: 9
It's the difference that comes from deep copy and shallow copy. Your problem will be solved by using deepcopy.
import copy
ad_material_name=['a', 'b', 'c']
ad_material_name2=['a', 'b', 'c', 'b']
for aa in ad_material_name:
asd=copy.deepcopy(ad_material_name2)
asd.remove(aa)
print(asd)
Upvotes: -1