3

My understanding of the Range function in python is that:

  • Range(beginning point, end point, amount to index by)

When the "amount to index by" is negative, you are basically going backwards, from the end towards the front.

My question is then:

  • When going in reverse, does the value at position -end point- not get evaluated?

For example, if I want to reverse a string "a,b,c" (I know you can just do string[::-1], but that's not the point here)

string = 'a,b,c'

strlist = list(string.split(","))

empty_list = []

for i in range((len(strlist)-1),-1,-1):
  print(strlist[i])

#this gets me "cba"

However when I change the end point from "-1" to "0" in the for loop, only "cb" gets printed:

string = 'a,b,c'

strlist = list(string.split(","))

empty_list = []

for i in range((len(strlist)-1),0,-1):
  print(strlist[i])

#this only gets me "cb"

Thanks for your time :)

3
  • Seems you answered your question already... Commented Feb 14, 2020 at 4:23
  • 5
    The end point is not included in the range, unlike the start point. Commented Feb 14, 2020 at 4:23
  • 1
    Does this answer your question? Reverse Indexing in Python? Commented Feb 14, 2020 at 4:24

1 Answer 1

2

What's happening in the first example is this:

for i in range((len(strlist)-1),-1,-1):
  print(strlist[i])

len(strlst) - 1 = 2, so when you use that as the beginning index for your for loop, that would obviously be the last letter, as it is indexed as 0, 1, 2. This will return the desired result of c, b, a.

When you have -1 for your end point, it will end after subtracting one from the iterator 3 times (2, 1, 0, ending when it reaches -1.)

for i in range((len(strlist)-1),0,-1):
  print(strlist[i])

Whenever you put in 0 as the end point, it will stop at position 0 of your list, or the first item. That would return c, b instead of c, b, a. Hope this helps.

Sign up to request clarification or add additional context in comments.

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.