0

suppose I have a list arr, and I want store this list elements by decreasing each element by 3, but if the number become negative after modification it should not be store How can i do that?

arr = [1, 5, 8, 10]

expected output>> arr1 =[2,5,7]

i am trying it like this using list comprehension but getting syntax error

arr1 = [x-3 if x is not < 0 else continue for x in arr]

can anyone help me to correct it , how can i do this by list comprehension?

  • `x is not < 0` doesn't make any sense. You probably wanted to write `x >= 0`. Also there is no such thing as `else continue` in a list comprehension. Just omit the `else` part. I also suggest you to start by learning Python before you attempt to write code in it. – Selcuk Aug 18 '21 at 03:58
  • Does this answer your question? [if/else in a list comprehension](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension) – leaf_yakitori Aug 18 '21 at 03:59

2 Answers2

2

Try this:

arr2=[x-3 for x in arr if x-3>0]

Output:

[2, 5, 7]
  • I want to ask you 2 things , I have a little doubts, , If you can explain a little 1st. x-3 > 0 (work fine) and x-3 >= 0 (why it will not work) 2nd. x-3 > 0 and x - 3 is not < 0 is it not same ? ( 4 -3 = 1 so 1 is not < 0 , it should store > i think , can you please help me to Understand, I know it may be silly doubts but still i am asking you – Pallab Tewary Aug 18 '21 at 04:14
  • @PallabTewary ```>=``` checks if the difference is **less than or equal to** 0 but ```>``` will check if difference is **greater than** 0 –  Aug 18 '21 at 04:15
1

Filters go at the end of the comprehension like this:

arr = [x - 3 for x in arr if x - 3 > 0]
kingkupps
  • 3,284
  • 2
  • 16
  • 28