What does index +=1 exactly do?

Hi! I understand that creating a loop, +=1 is used to raise the index by 1 until a certain condition is met.
But changing to another value, let’s say +=n, I would have expected that the action is repeated for every n.th value of the list.
Taking the given example of

all_students = [“Alex”, “Briana”, “Cheri”, “Daniele”, “Dora”, “Minerva”, “Alexa”, “Obie”, “Arius”, “Loki”]
students_in_poetry =
students = 0
while students < 6:
students +=1

returns [‘Loki’, ‘Arius’, ‘Obie’, ‘Alexa’, ‘Minerva’, ‘Dora’]

Why does changing students +=1 to students +=7, for example, return [‘Loki’]?

students +=1 is exactly the same how students=students+1. It’s the short written form for icrementing students by one. So your while is running until students is 5. Pop returns the last value of the list. and it is append on a new list so this code gives you the last 5 students.

If you change it too +=7 you increment students to 7 in the first run which is returning “Loki” and finish after this. You can write the print in the while to see what happens round for round

students is here not your index. It is only used too to do a action while students condition is true

thanks for the quick response! Got it now!

1 Like

To answer your question about why using students += 7 causes the output t be ['Loki'], consider what the new value of students is after executing that line, and then look at the condition of your while loop. Can you see why the output would be ['Loki']? (Hint: how many times does your while loop execute?)

1 Like

You seem to have got the answer, but ill add some weird behaviour I discovered by accident with the += syntax.

So for some reason when I type += my brain sometimes thinks its =+ (for some reason this just seems more intuative syntax to me), however this seems to be intepreted as "=(positive number) "so:

i =+ 1

is identical to:

i = 1

If you ever notice a while keeps going infinite but isnt throwing errors, try this.