Search code examples
pythontuplesbubble-sort

How to I assign the value of one item in a tuple to another in Python?


I need to sort items in a tuple using the bubble sort method for a project in my computer science class. The items are all integers.

   SwapAgain = True
    
    while SwapAgain == True:
        SwapAgain = False
        for item in xrange(len(mytuple)):
            if mytuple[item] > mytuple[item + 1]:
                SwapAgain = True
                temp = mytuple[item]
                mytuple[item] = mytuple[item + 1]
                mytuple[item + 1] = temp
                
    return mytuple

I'm trying to assign the value of one item in the tuple to another, but when I try the code above I get this error:

mytuple[item] = mytuple[item + 1]

TypeError: 'tuple' object does not support item assignment

I would have preferred to use a list, but my teacher only provided us with a specific tuple. I really appreciate any help I can get. Thanks!


Solution

  • A tuple is an immutable data type. Once you create it, you can't alter it. So doing this with a list would make sense, and you have the option to return a tuple when the sorting is done, for example:

    SwapAgain = True
    myList = list(myTuple)
    
    while SwapAgain == True:
        SwapAgain = False
        for i in xrange(len(myList)):
            if myList[i] > myList[i + 1]:
                SwapAgain = True
                temp = myList[i]
                myList[i] = myList[i + 1]
                myList[i + 1] = temp
    
    return myList # or return tuple(myList) if you want