0

the range function has syntax range(start,stop,step) and returns a sequence based on the arguments. Please explain the syntax range(10)[2:6][2]

range(10) is identical to range(0,10,0). what is happening with '[2:6][2]?

thanks

entering range(10)[2:6][2] evaluates to 4, but I don't understand why.

Progman
  • 16,827
  • 6
  • 33
  • 48

2 Answers2

0

The range function in Python has the syntax range(start, stop, step) and generates a sequence of numbers starting from start, up to but not including stop, with a step size of step. In the case of range(10), this generates a sequence of numbers starting from 0 and up to but not including 10, with a step size of 1. Note that the default value for the start parameter is 0 and the default value for the step parameter is 1, so range(10) is is identical to range(0,10,1) rather than range(0,10,0) as you indicated in your post.

You can find documentation for the range built-in function at: http://docs.python.org/3/library/functions.html#func-range and https://docs.python.org/3/library/stdtypes.html#typesseq-range

The square brackets after the range function are used to index the resulting sequence. For example, range(10)[2:6] returns a sub-sequence of numbers starting from the 3rd element (index 2) and up to but not including the 6th element (index 5), which in this case is [2, 3, 4, 5].

The second set of square brackets then indexes this sub-sequence, returning the 3rd element. Therefore, the expression range you provided evaluates to 4.

You can find documentation for the slicing syntax at: https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html

Brandon E Taylor
  • 24,881
  • 6
  • 47
  • 71
  • perfect answer, but where is that explained in documentation? (feeling stupid) – Thomas Mathew David Loeff Dec 09 '22 at 23:37
  • range function is described at : https://docs.python.org/3/library/functions.html#func-range. Note that range(10) is identical to range(0,10,1) rather than range(0,10,0) – Brandon E Taylor Dec 09 '22 at 23:47
  • The syntax for slicing can be found at: https://python-reference.readthedocs.io/en/latest/docs/brackets/slicing.html – Brandon E Taylor Dec 09 '22 at 23:48
  • @ThomasMathewDavidLoeff This particular syntax probably isn't explained in the documentation because there isn't really a practical use for it. Even `range(2, 6)[2]` doesn't have a practical use. – nigh_anxiety Dec 10 '22 at 00:13
0

range(param) is a build-function that generate a list. The param is the lenght of number of list. So you have a list of 10 numbers. From 0 to 9. Remenber arrays become at the 0 position. Then you slice the list with [start,end, jumps]. You slice the list. The result is 2,3,4,5. After that you call the number at position [2].

  • Beginning from 0 => 2
  • Next position 1 => 3
  • Then position 2 => 4