 # How index operator works? I'm so confused

How the index operator works in Python? I’m always stuck in this… From the following code, You can see that we used the for loop to iterate through user_name. We added the username data to password variable. Why there is a username[i-1]? If it’s i minus 1, then there should be 5 characters. How the character “p” replaced to the first index of the username string? Can anyone give me good explanation about the index operator.

Thanks alot

``````password = ""

for i in range(0, len(user_name)):

``````

When you use single negative value to index in Python you start indexing from the end of the list. Larger negatives begin to step towards the start of the list one at a time.

A quick example (I used a list but the indexing works the same)-
Hopefully this formats nicely…

``````# idx is the standard index we used
idx =   0,   1,   2
lst = ['a', 'b', 'c']
idxn = -3,  -2,  -1
# with negatives we can address the same values with idxn
# with the given list above: lst...
lst == lst[-1]
lst == lst[-2]
lst == lst[-3]
# For a larger list these patterns would continue
# e.g. lst == lst[-101] assuming the index goes that high
``````

If you then consider the values that `i - 1` takes can you see how it has shifted the characters in the username?

If not, perhaps you could `print` out the value of `i - 1` at each step of the loop and then work with the index from there in the same way the example above does.

2 Likes