Search code examples
pythonxrange

list of random integers without zero Python


I need a random list of integers without 0. I'm using random.sample(xrange(y),z) but I don't want 0 in this list. Thank you


Solution

  • Start your range at 1 then:

    random.sample(xrange(1, y), z)
    

    That's all there is to it, really.

    Demo:

    >>> list(xrange(3))
    [0, 1, 2]
    >>> list(xrange(1, 3))
    [1, 2]
    

    xrange() doesn't just produce a series of integers up to an endpoint, it can also produce a series between two points; a third option gives you a step size:

    >>> list(xrange(1, 6, 2))
    [1, 3, 5]