-4

I have recently started learning Python and wanted to try bubble sort. I'm getting the desired output, but is there a way to not have the space after the final element?

My Output (0 1 2 4 4 5 7 9 14 18 18 )

The output I want (0 1 2 4 4 5 7 9 14 18 18)

Ignore the brackets, they are to show the space

def bubble(arr):
    n=len(arr)
    for i in range(n-1):
        for j in range(0,n-i-1):
            if arr[j]>arr[j+1]:
                arr[j], arr[j+1]= arr[j+1], arr[j]
    for k in range(n):
        print(arr[k],end=" ")
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Mugdha
  • 1
  • 1
  • 2
    Whole sorting part is irrelevant since your question is purely about printing the list. – matszwecja Feb 01 '22 at 15:38
  • You can just do `print(arr)`. If you don't like the format, then `print(tuple(arr))`. – trincot Feb 01 '22 at 15:39
  • My Output and The output I want are exactly the same. You mean just the last space between 18 and )? –  Feb 01 '22 at 15:39
  • 2
    @SembeiNorimaki no they're not, `My Output` has a space at the end. Problem is, this question is about printing the output, not about sorting. – Shinra tensei Feb 01 '22 at 15:40
  • "is there a way to not have the space after the final element?" Yup, don't print it. You are currently printing a space after every element with `end=" "`. You will need to do something that treats the last element differently. – Code-Apprentice Feb 01 '22 at 15:41

1 Answers1

1

You can use transform each integer into a string using str(), then use " ".join to avoid having to print the trailing space.

print(" ".join(str(item) for item in arr))
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33