What does index += 1

Screen Link:

My Code:

#Remove the “Details”
index = 0

for row in data:
data[index]=row[:-1]
index = index +1

print(data[:3])

I’m struggling to understand why we need the "index +=1 ". Could someone please help? Thank you!

Hey @miah

index += 1 and index = index + 1 mean the same thing.

Till the time the loop executes, the index variable will keep adding 1 to itself.

2 Likes

Hi @Rucha,

Thanks for explaining. Would you be able to elaborate more? Especially on the part that the loop executes.

If I understand it correctly, the code above will remove the last element of the dataset, and it keeps doing that until the very end of the dataset, hence the index needs to +1 to move the loop to the next row?

Hi @miah

Yes. you understand it correctly! :+1:

The code data[index] = row[:-1] excludes the last element from current index position. But since we want the loop to execute for all the rows we need to update the value of the index variable to the total length of the data list.

To do so we have to increase it by 1. Or else it will always remain at 0.

1 Like

Hi Rucha - thanks so much! Appreciate your help :slight_smile:

1 Like