FateCoreUloom
FateCoreUloom

Reputation: 463

Range indexing in Python

My understanding of the Range function in python is that:

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

My question is then:

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 :)

Upvotes: 3

Views: 1428

Answers (1)

OakenDuck
OakenDuck

Reputation: 483

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.

Upvotes: 2

Related Questions