Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range indexing in Python

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

like image 885
FateCoreUloom Avatar asked Apr 11 '26 22:04

FateCoreUloom


1 Answers

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.

like image 104
OakenDuck Avatar answered Apr 14 '26 12:04

OakenDuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!