[Python] How to add an integer (+1) to the items of a list except if they have a specific...

Discussão em 'Python' iniciado por Stack, Setembro 2, 2025.

  1. Stack

    Stack Membro Participativo

    I want to add 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. I want it to show all 3 items but don't add anything to those that are 3.

    Then I tried this but it still doesn't work:

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

    Continue reading...

Compartilhe esta Página