python lists, appending something to the list changes the entire thing?

后端 未结 3 1613
一个人的身影
一个人的身影 2021-01-28 08:18

so im trying to implement selection sort in python.. and im appending the result of each iteration to a list to print at the end.. my code sorts the list of numbers properly but

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-28 08:32

    I don't see the actual sort that you're doing, but in general:

    Lists are mutable. Any change you make to it affects all links to that list. To make a copy of it and break its connection to other references, you need to return alist[:]

    def s_sort(numbers):
      alist=[]
      #do actual sorting here and swap numbers/index if neccessary
    
           alist.append(numbers)
      return alist[:]  # this makes it a copy!
    
    def main():
        numbers=[5,7,3]
        print(s_sort(numbers))
    main()
    

提交回复
热议问题