osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

ValueError vs IndexError, unpacking arguments with string.split


On Sun, Dec 2, 2018 at 10:36 PM Morten W. Petersen <morphex at gmail.com> wrote:
> While we're on the subject, I did a test in my Python interpreter:
>
> Python 3.6.7 (default, Oct 22 2018, 11:32:17)
> [GCC 8.2.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> range(0,3,100)
> range(0, 3, 100)
> >>> len(range(0,3,100))
> 1
> >>> range(0,100)
> range(0, 100)
> >>> len(range(0,100))
> 100
> >>>
>
> Where a range with a step, gives the length 1, while a plain range gives
> the right length.
>
> I think that's confusing and inconsistent, and it would be nice to have some
> "value to be calculated" for the length integer as well.
>

Possibly you're misinterpreting the arguments here.

>>> list(range(0, 3, 100))
[0]

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |

The *third* argument is the step, so if you were expecting "every
third number up to 100", you'd be looking for this:

>>> len(range(0, 100, 3))
34
>>> len(list(range(0, 100, 3)))
34

To my knowledge, len(x) == len(list(x)) for any core data type that
has a length.

ChrisA