0

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

4 Answers4

1

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]
AChampion
  • 29,683
  • 4
  • 59
  • 75
1

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
Jab
  • 26,853
  • 21
  • 75
  • 114
0

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]
Halbert
  • 142
  • 7
0

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

[x + (x != 3) for x in p]
no comment
  • 6,381
  • 4
  • 12
  • 30