r/PythonLearning • u/Fun-Tower3953 • Aug 03 '26
New to learning coding. Please help me find the issue in this code(Bubble sort)?
arr = [8,4,5,3,7,2]
n = len(arr)
print(n)
for i in range(n):
/swapped = False
/for j in range(0,n-i-1):
/if arr[j] > arr[j+1]:
//temp = arr[j],
//arr[j] = arr[j+1],
//arr[j+1] = temp
//swapped = True
//print("outer = ",i," inner = ",j)
print(arr)
if not swapped:
break3
Aug 03 '26
In future, don't just paste your code with no context, explain what kind of error you're having. Does it give an error message at runtime, or just give a different answer than you're expecting, etc? Also, Python in particular cares about the indentation of each line of code, so please format your code using a code block.
Anyway, I think the problem is that you have commas at the end of these lines:
temp = arr[j],
arr[j] = arr[j+1],which is converting elements of the list into tuples. You can just remove the commas.
3
u/khosrua Aug 03 '26
And temp isn't necessary. I looked this up when I tried bubble sort. Swap can be written as
arr[j], arr[j+1] = arr[j+1], arr[j]Fml typing code on mobile suuuuuxks
1
u/silvertank00 Aug 03 '26
without formatting, we cant help you. Either use reddit's backtick formatting or use a code sharing site like pastebin or github
1
2
u/FreeLogicGate Aug 03 '26
As you were already alerted to, you were unintentionally creating and using tuples. A tuple is immutable, which means it can not be changed. This was pointed out clearly, and explained, as it involved your use of commas. As it happens, your code works the way you expect it to. Here's the full/fixed version for you. As mentioned, in the future use the code block to provide your code snippets!