Range and length

I am hoping for just a little better explanation on using range and length in a function. I don’t have to look at solutions very much before hand, but for some reason using these two just aren’t clicking in my head. i am currently doing the review of strings and the last task is:

" Inside password_generator create a for loop that iterates through the indices username by going from 0 to len(username). To shift the letters right, at each letter the for loop should add the previous letter to the string password. "
" Remember, you can use range(x,y) to generate a list of values between x and y (including x and excluding y ). This is how you should iterate through the username."

I completed the lesson, but i had to use the solution for this function. What I am looking for is if someone can break down each step of the for loop below as to what it’s doing and why. Usually if i can understand it then i will have no problem implementing it later, but clearly im not getting something. I get that its moving the last letter to the front, but not why. Thanks a lot for any help!


One way to visualize what code is doing is to add print statements. You could also use various debugging tools or code visualizers like pythontutor.com.
For future posts that include code, it would be helpful if you post the code between lines of 3 backticks to preserve formatting rather than a screenshot.

Code Goes Here


The range() method creates a range object that starts with the first argument, and goes up to, but does not include the second argument. So, for example, range(0, 5) gives you a range object including the values: 0, 1, 2, 3, 4. In your example, the length of user_name is 6, so range(0, len(user_name)) returns a range object including the values: 0, 1, 2, 3, 4, 5 which are the valid indices for a string with 6 characters.

string:      | j | o | s | c | h | m |
indices:     | 0 | 1 | 2 | 3 | 4 | 5 |

Keep in mind that Python allows for negative indices as well with -1 referring to the last element.

string:               | j | o | s | c | h | m |
negative indices:     |-6 |-5 |-4 |-3 |-2 |-1 |

Adding print() statements we can follow what is happening.

def password_generator(user_name): password = "" for i in range(0, len(user_name)): print("i is:", i) print("user_name[i-1] is:", user_name[i-1]) password += user_name[i-1] print("password is now:", password) return password print(password_generator("joschm"))

Seriously, thank you so much! I don’t know why this was so hard for me to conceptualize, but it makes a lot more sense. Thank you for the amount of effort you put into the reply!

1 Like