disappear element in python

Viewed 72
classes = [['A', 'B', 'C', 'D', 'G', 'H'], ['B', 'C', 'E', 'G', 'H', 'K', 'L'], ['C', 'E', 'D', 'H', 'K', 'L'], ['E', 'D', 'F', 'K', 'L'], ['D', 'G', 'H'], ['F', 'K'], ['G', 'F'], ['H', 'L'], ['K', 'H', 'L'], ['L']]

        
def get_parents(child,classes): 
    for element in classes:
        if element[0] == child:  
            parents_list = element
            parents_list.remove(child)
            return parents_list   
        
        
def check(parent, lst):
    for each_element in lst:
        if parent in each_element:
            return 'Yes'
    return 'No'

def prove(lst,parent):
    if parent in lst:
        return 'Yes'
    else:
        return 'No'


print (prove(get_parents('D',classes.copy()),'K'))

print(classes)
print (get_parents('D',classes))

print (check('A',classes))

Why when I run this code, my func get_parents() delete 'D' from list 'classes' [D,G,H]? I guess, that parents_list.remove(child) deleting copied element in namespace def that i put in parents_list, but it changed global data without direct command.

Why this f*cking python so lazy, that can't dedicate some memory to new object, but just linked my var to data in list?!

1 Answers

In the get_parents function, you are referencing the element. Which is still linked to your classes collection. By creating a copy you remove the reference. So the fix to your problem is parents_list = element.copy().

More information about the copy statement can be found here.

[btw, shadowing variable names is probably not the best idea and cause confusing results]

Related