0
alph = list("abcdefghijklmnopqrstuvwxyz")
swap = True
items = ["bob","clara","adam"]
itemsBackup = items
print(itemsBackup)
while swap:
    print("x")
    for i in range(len(items)):
        if i == len(items)-1:
            print("a")
        elif alph.index(items[i][0]) > alph.index(items[i+1][0]):
            temp = items[i]
            items[i] = items[i+1]
            items[i+1] = temp
            swap = True
            print("z")
    if itemsBackup == items:
        print(itemsBackup)
        swap = False

Ignore the printing of x, z and a by the way.

What happens when I run the code is that itemsBackup gets changed from ["bob","clara","adam"] to ["bob","adam","clara"] even though I didn't try to make this change happen. Does anyone know why? Thanks.

cs95
  • 379,657
  • 97
  • 704
  • 746
Daniel
  • 69
  • 1
  • 2

1 Answers1

1

itemsBackup is still pointing to items, therefore it is looking at the same list.

try using:

itemBackup = item[:]

This makes a copy of the list by slicing it.

mij
  • 532
  • 6
  • 13