Home > database >  How to add an integer ( 1) to the items of a list except if they have a scpecific value in Python
How to add an integer ( 1) to the items of a list except if they have a scpecific value in Python

Time:10-05

Hi I'm really new to programming. I want to add 1 ( 1) to each item in a list, except for the items that have value = 3. I tried with a for loop:

p = [1,2,3]
p= [x 1 for x in p if x != 3]
print (p)
#[2,3]

But the output is [2,3], so it adds 1 to the first to items but doesn't output the last one. That's not what I want, I wan't it to show all 3 items but don't add anything to those who are = 3.

Then I tried this but still doesn't work:

p = [1,2,3]
p= [x 1 for x!=3 in p]
print (p)
#SyntaxError: invalid syntax

CodePudding user response:

As you have found the guard expression [<expr> for x in p if <guard>] will filter the list to only those that meet the guard expression.
As you are looking to work on every value then you should not use guard but look at the ternary operator (aka Conditional Expressions):

[x 1 if x != 3 else x for x in p]

CodePudding user response:

Since booleans are also integers you can just add the result of the condition to the value:

[x   (x!=3) for x in p]

And if you wanna get fancy you can use numpy:

p[p!=3]  =1

CodePudding user response:

Your code is only selecting those elements of p not equal to 3. Instead, you need to the conditional applying to the outcome:

[x 1 if x != 3 else x for x in p]

CodePudding user response:

Just another way, using that bools act like 0 and 1:

[x   (x != 3) for x in p]
  • Related