Why do I get extra spaces in an integer list while doing list operations in python3?

43 Views Asked by At
num = [100,1,82,-1]
print(sorted(num))

The above piece of code give the following output: [-1, 1, 82, 100]. However, I need it to be like [-1,1,82,100]. But so far I have been unable to figure out why does Python add whitespaces in a list with any kind of list operation! Even a simple addition, or list methods like extend(), sort(), etc provide an output with leading whitespaces.

Although they shouldn't really matter, I am trying to solve a leetcode question, where my answer is getting rejected due to these leading whitespaces.

2

There are 2 best solutions below

1
Ritvik The God On

You can create a custom list type like below and then override how it is printed, if necessary for debugging purposes:

class SortMeOnPrint(list):
    def __repr__(self):
        return str(sorted(self)).replace(' ', '')


num = SortMeOnPrint([100,1,82,-1])
print(num)  # [-1,1,82,100]

And if needed, you could also generalize that into a helper function, to eliminate minor overhead of a new type itself:

def print_wo_spaces(L):
    print(str(L).replace(' ', ''))

num = [100,1,82,-1]
print_wo_spaces(sorted(num))  # [-1,1,82,100]
0
shaarang.pd On

The output follows an English like syntax where the commas are followed with blank spaces, even though you like it or not. xD You can change it the way you want by overriding the method.