-4

i can't understand this convention range in python, range(len(s) -1) for representing all elements including the last one. For me makes no sense like when I print all elements the last one is not included in the list. Someone could help me understand this logic?

this>

s = "abccdeffggh"
for i in range(len(s) -1):
    print(i)

result this

0
1
2
3
4
5
6
7
8
9
Community
  • 1
  • 1
  • https://stackoverflow.com/questions/4504662/why-does-rangestart-end-not-include-end – mkrieger1 Jun 11 '20 at 16:41
  • 1
    `range(3)` iterates 3 times. `range(len(s) - 1)` iterates `len(s) - 1` times. What's confusing about that? – r.ook Jun 11 '20 at 16:41
  • Why are you using `len(s) - 1`? That specifically tells it to use one _less_ than the number of elements, so of course it skips the last one. – John Gordon Jun 11 '20 at 16:43
  • def count_adjacent_repeats(s): ''' (str) -> int Return the number of occurrences of a character and an adjacent character being the same. >>> count_adjacent_repeats('abccdeffggh') 3 ''' repeats = 0 for i in range(len(s) - 1): if s[i] == s[i + 1]: repeats = repeats + 1 return repeats – Walnei Oliveira Jun 11 '20 at 17:40
  • because I need to interate with all elements inclusive with the stop element in this function. Thanks for your feedback! – Walnei Oliveira Jun 11 '20 at 17:41

1 Answers1

-1

you are trying to print range to compiler you saying like this print numbers greter than 1 and below than 10 to the output not include 1 and 10 compiler only print 2,3,4,5,6,7,8,9 in your case

s = "abccdeffggh"

this s string length must be 11 if you print like this

s = "abccdeffggh"
for i in range(len(s)):
    print(i)

you get output as 1,2,3,4,5,6,7,8,9,10 that is the numbers between 0 and 11

but in your code you have subtract -1 from the length then your range is become -1 and 10 then compiler print all numbers between the -1 and 10 it not include -1 and 10

try this code

s = "abccdeffggh"
print(len(s))
print(len(s)-1)
for i in range(len(s)):
    print(i)
Buddhika Prasadh
  • 356
  • 1
  • 5
  • 16
  • I need to interate with all str elements in this function: but the range functions stops at the last element.. def count_adjacent_repeats(s): ''' (str) -> int Return the number of occurrences of a character and an adjacent character being the same. >>> count_adjacent_repeats('abccdeffggh') 3 ''' repeats = 0 for i in range(len(s) - 1): if s[i] == s[i + 1]: repeats = repeats + 1 return repeats Thanks for your feedback. – Walnei Oliveira Jun 11 '20 at 17:44