Home > Software engineering >  Error while sorting list in lambda mode which works fine in if else statement
Error while sorting list in lambda mode which works fine in if else statement

Time:08-18

Only asc is running and if any other number is added it gives error. Code is given below

    ```y=input("Write 'asc','dec', 'none'")
       converter=lambda x:sorted (x) if y=="asc" else (sorted(x,reverse="True" if y=="dec" else y))
       print (converter (x=[1,2,4,6,10,0, 8, 5]))```

CodePudding user response:

This is because the reverse argument requires a boolean, not a string (True or False, not "True", because "True" is a string).

from w3school tutorial:

reverse=True will sort the list descending. Default is reverse=False

So it should be:

y=input("Write 'asc','dec', 'none'")
converter=lambda x:sorted(x, reverse=y=="dec") if y != "none" else x
print (converter (x=[1,2,4,6,10,0, 8, 5]))

edit: Alexander's answer assumes that you expect "none" and "asc" to work in the exact same way (sort in ascending order), I assume that you want to return the original list without sorting when "none" is passed, it is not clear which is your expectation according to the question

CodePudding user response:

You are using the wrong value for the reverse argument in your second sorting function. The value must be True or False.

I can confirm that this works as expected.

y=input("Write 'asc','dec', 'none'")
converter=lambda x:sorted (x) if y=="asc" else (sorted(x,reverse=True if y=="dec" else False))
print (converter (x=[1,2,4,6,10,0, 8, 5]))

However your code is doing the same thing as this code which is much easier to understand:

print(sorted([1,2,4,6,10,0,8,5], reverse=input()=="desc"))
  • Related