.sort()
is not working as I expect it to. I intended to create a Python program that sorts two copies of the same array in ascending and descending order.
Initial code
def MyFunction(Num):
StrNum = str(Num)
ArrNum = [letter for letter in str(Num)]
print(ArrNum)
print('Ascending and Descending Arrangements')
AscendingNum = ArrNum
DescendingNum = ArrNum
DescendingNum.sort(reverse=True)
print(DescendingNum)
AscendingNum.sort()
print(AscendingNum)
MyFunction(1032)
Result
DescendingNum = ['3', '2', '1', '0']
AscendingNum = ['0', '1', '2', '3']
I reprinted them.
Result with ascending sorted last
DescendingNum = ['0', '1', '2', '3']
AscendingNum = ['0', '1', '2', '3']
Result with descending sorted last
DescendingNum = ['3', '2', '1', '0']
AscendingNum = ['3', '2', '1', '0']
My guess at why it is happening
It appears that the second sorting is affecting the first. Although I have read many articles on .sort()
, I cannot grasp why this is happening; after all, they are two separate arrays. Yet, I feel that the reason might lie in the following part.
AscendingNum = ArrNum
DescendingNum = ArrNum
What is the reason and solution?