1

This could be a very basic question, but I realized I am not understanding something.

When appending new things in for loop, how can I raise conditions and still append the item?

For instance:

alist = [0,1,2,3,4,5]
new = []
for n in alist:
    if n == 5:
        continue
    else:
        new.append(n+1)

print(new) 

Gets me

[1, 2, 3, 4, 5]

How do I get

[1, 2, 3, 4, 5, 5] # 4 is incremented, 5 is added 'as is'

Essentially, I want to tell python to not go through n+1 when n==5.

Would this be the only solution? append n==5 separately in a list and then sum new and the separate list?

3
  • new.append(n) rather than continue? Commented Oct 22, 2018 at 2:51
  • new = [1, 2, 3, 4, 5, 5]? Commented Oct 22, 2018 at 2:54
  • @StephenRauch I'd like to get the result using the for loop Commented Oct 22, 2018 at 2:56

3 Answers 3

8

Why don't you just append the 5 instead of using continue, is there any other condition?

for n in alist:
    if n == 5:
        new.append(n)
    else:
        new.append(n+1)
Sign up to request clarification or add additional context in comments.

1 Comment

Right, use append because it appends sequentially! Make sense. Thank you!
2

You can use the fact the a boolean True is 1 while a False is 0 combined with a list comprehension like:

Code:

[x + int(i != 5) for i, x in enumerate(alist)]

Test Code:

alist = [0, 1, 2, 3, 4, 5]
new = [x + int(i != 5) for i, x in enumerate(alist)]
print(new)

Result:

[1, 2, 3, 4, 5, 5]

Comments

1

Seems like you didn't get the point of 'continue'. The Python keyword 'continue', means you do nothing in that if condition, so basically you tell the program "do nothing" when n == 5 and if n is not 5, you do some operation. That's why you got your original result. Hope it may help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.