-2
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.

  • 1
    This has nothing to do with "list operations", this is simply how lists are printed out, as implemented in `list.__str__`. Try, `num = [100,1,82,-1]; print(num)` Why does it matter? – juanpa.arrivillaga Sep 01 '22 at 17:06
  • what's the use case? are you trying to serialize to a format like json, or just want to remove spaces for debugging purposes or similar? – rv.kvetch Sep 01 '22 at 17:06
  • note, the spaces aren't "added" to the list. – juanpa.arrivillaga Sep 01 '22 at 17:07
  • 1
    The spaces in the printed output shouldn't matter unless you have a reason for them to; but you have not explained any such reason. Therefore, it's my thought that you might be trying to find a solution for the wrong problem - this is called the "XY problem" and there's more info about it here: https://xyproblem.info/ – Random Davis Sep 01 '22 at 17:08
  • I am trying to solve a CP question, and that seems to differentiate between lists with and without leading whitespaces, and my answer is not getting accepted @rv.kvetch – Shashank Priyadarshi Sep 01 '22 at 17:09
  • 1
    sorry, unfamiliar with acronyms but curious to know what is CP? – rv.kvetch Sep 01 '22 at 17:11
  • Where is that CP question? Link? I rather doubt that this is your problem. – Kelly Bundy Sep 01 '22 at 17:18
  • Which leetcode question is it? – Kelly Bundy Sep 01 '22 at 17:46
  • https://leetcode.com/problems/merge-sorted-array/ @KellyBundy this was the question I was trying to solve, and the problem was indeed not with the spaces in the list but the my array operations not happening in place. – Shashank Priyadarshi Sep 02 '22 at 06:54

2 Answers2

0

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]
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
0

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.