Pallab Tewary
Pallab Tewary

Reputation: 123

how can i use If-else and for loop both in list comprehension

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?

Upvotes: 0

Views: 87

Answers (2)

kingkupps
kingkupps

Reputation: 3504

Filters go at the end of the comprehension like this:

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

Upvotes: 1

user15801675
user15801675

Reputation:

Try this:

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

Output:

[2, 5, 7]

Upvotes: 2

Related Questions