0

I know that I should write a code to random numbers like the code below, but I don't know how to generate unique numbers, for example I want to generate 3 unique phone numbers from a list at once, how can I do it?

import random  

# last numbers of the phone numbers are in order, 1,2,3,4,5,6
myList = [60165651, 60175652, 60156523, 60135354, 60159535, 60192326]  

for x in range(5): 
    print(random.choice(myList))

-----------------------------------------------------

another problem is that if I put zero at the beginning of numbers I get an error: Token invalid!

e.g:

myPhoneList = [060165651, 60175652, 60156523, 60135354, 60159535, 60192326]
smci
  • 32,567
  • 20
  • 113
  • 146
sf31
  • 45
  • 3
  • 10
  • 1
    You're trying to ***sample*** the input list of numbers, not ***generate*** it (as an output). – smci Sep 28 '19 at 08:28
  • 1
    And sampling N unique items is called ***sampling without replacement***. See the doc for [`random.sample`](https://docs.python.org/3/library/random.html?highlight=random.sample#random.sample) – smci Sep 28 '19 at 08:29
  • 2
    2nd issue: Putting zero at the beginning of a number tells Python it's octal (base-8), but then your number can't contain the digits 8,9, that's why it throws an error. Duplicate of [this](https://stackoverflow.com/questions/29778699/python-syntaxerror-invalid-token-on-numbers-starting-with-0-zeroes). So if you really want to have a decimal phone number with leading zero, use a list of strings, not integers. – smci Sep 28 '19 at 08:36
  • 1
    There is a special module `faker` to generate a fake data. You can use it to get fake numbers as well. – Mykola Zotko Sep 28 '19 at 08:39

1 Answers1

1

Use random.sample:

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

from random import sample

myList = [60165651, 60175652, 60156523, 60135354, 60159535, 60192326]  
print(sample(myList, 3))
# [60192326, 60165651, 60175652]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50