two operations on each element of a list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



two operations on each element of a list



I would like to achieve the following lines in just one line:


list1 = [abs(x) for x in list1]
list1 = list(map(lambda x:x-1, list1))



I tried


list1 = [abs(x) and x-1 for x in list1]



even though I don't think there is such syntax, but anyway it didn't work.





[abs(x)-1 for x in list1] is it what you want?
– Saeed
Aug 12 at 2:49




2 Answers
2



and is a logical operator in Python, it cannot be used in this condition.


and



why not try


[abs(x) - 1 for x in list1]





thx, do you know if we can do two operations in other cases in just one line?
– Lelo
Aug 12 at 3:02





@Lelo it's ok, you can use lambda to do the more complicated operation in one line. And how to achieve it depends on what the problem is.
– pwxcoo
Aug 12 at 3:05



lambda





what do you mean @Lelo? You can string lambda functions together, if that interests you
– kevinkayaks
Aug 12 at 3:05


list1 = list(map(lambda x: abs(x)-1,list1))



Interestingly this is slower than


list1 = [abs(x) - 1 for x in list1]



Anyone know why?






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered