[Solved] Python 3: How to get a random 4 digit number?


If you want to extend your solution to make sure the leading digit isn’t 0, there’s probably no super-concise way to write it; just be explicit:

first = random.choice(range(1, 10))
leftover = set(range(10)) - {first}
rest = random.sample(leftover, 3)
digits = [first] + rest

Notice that I’m taking advantage of the fact that sample takes a sequence or set. In older versions of Python, it required a sequence. According to the 2.7 docs, this includes 2.7—but CPython and PyPy 2.7 both take a set anyway. Anyway, if this is a problem, you can just do leftover = [val for val in range(10) if val != first].


One more thing to consider, if performance matters. A nondeterminstic solution like noskio’s answer obviously has unbounded worst-case time, but it could be significantly faster in almost every case. There’s a 90% chance you’ll get your answer the first time, and a 99.9999999% within the first ten loops, and it’s at least plausible that a single call to sample could be about an order of magnitude faster than multiple set operations, etc.

solved Python 3: How to get a random 4 digit number?