My question is : I have a function in python which takes a dictionary and a string as input. This dictionary has strings as keys as lists as values. In function dictionaries lists are changed - entries removed as they are used until first empty list in values is hit. For one run it works well, but when this function is in a for loop changing only input string and using the very same dictionary, with each iteration original input dictionary is changed. This is despite in function by the first step I create a new dictionary setting it equal to input and make all changes on that new dictionary. Could you give me a hint of what is wrong? Why original dictionary is affected? Also I got the same when I create a new list in for loop before function and pass this new list as input.
Here is an actual code :
#reading an input file
x=open('graph .txt')
data=[line.strip() for line in x.readlines()]
gr=[s.split(' -> ') for s in data]
#creating a graph
graph={}
for i in gr:
graph[i[0]]=list(i[1])
for val in graph.values():
if ',' in val:
val = val.remove(',')
cycle=[]
nums=graph.keys()
# function changing dictionary
def path(start,graph):
cycle=[]
graph111=graph
cycle.append(start)
while graph111[start]!=[]:
move=graph111[start]
if move==[]:
break
if len(move)>1:
n=''.join(move[0])
start=n
cycle.append(n)
else:
p=''.join(move)
start=p
cycle.append(p)
move.remove(move[0])
return ('->'.join(cycle))
# for loop:
for num in nums:
c=path(num,graph)
cycles.append(c)
input looks like this:
0 -> 3
1 -> 0
2 -> 1,6
3 -> 2
4 -> 2
5 -> 4
6 -> 5,8
7 -> 9
8 -> 7
9 -> 6