random - Python sample without 0 -
i need sample k numbers in [-n,-1] union [1,n] without replacement. why doesn't code work?
random.sample(range(-n,n+1).remove(0),k)
i
traceback (most recent call last): file "<input>", line 1, in <module> file "/usr/lib/python2.7/random.py", line 319, in sample n = len(population) typeerror: object of type 'nonetype' has no len()
remove
inplace operation. modifies list, , returns none. that's why seeing error. should create list separately , pass sample
:
>>> l = range(-n, n+1) >>> l.remove(0) >>> random.sample(l, k)
if want in 1 statement, create 2 parts of range separately , add them.
>>> random.sample(range(-n, 0) + range(1, n+1), k)