d={1:[2, 3], 2:[3], 3:[5], 4:[1], 5:[]} hallid=[1] mustad=[] while hallid: for tipp in d[hallid[0]]: if tipp not in hallid+mustad: hallid.append(tipp) mustad.append(hallid.pop(0)) print(hallid) print(mustad)