6

So I just started programming in Python a few days ago. And now, im trying to make a program that generates a random list, and then, choose the duplicates elements. The problem is, I dont have duplicate numbers in my list.

This is my code:

import random

def generar_listas (numeros, rango):
    lista = [random.sample(range(numeros), rango)]
    print("\n", lista, sep="")
    return
def texto_1 ():
    texto = "Debes de establecer unos parámetros para generar dos listas aleatorias"
    print(texto)
    return

texto_1()
generar_listas(int(input("\nNumero maximo: ")), int(input("Longitud: ")))

And for example, I choose 20 and 20 for random.sample, it generates me a list from 0 to 20 but in random position. I want a list with random numbers and duplicated.

1
  • You could sample from a container that has duplicates. Assuming python2.x: random.sample(range(20) + range(20), 20) Commented Sep 7, 2016 at 21:51

2 Answers 2

10

What you want is fairly simple. You want to generate a random list of numbers that contain some duplicates. The way to do that is easy if you use something like numpy.

  • Generate a list (range) of 0 to 10.
  • Sample randomly (with replacement) from that list.

Like this:

import numpy as np
print np.random.choice(10, 10, replace=True)

Result:

[5 4 8 7 0 8 7 3 0 0]

If you want the list to be ordered just use the builtin function "sorted(list)"

sorted([5 4 8 7 0 8 7 3 0 0])
[0 0 0 3 4 5 7 7 8 8]

If you don't want to use numpy you can use the following:

print [random.choice(range(10)) for i in range(10)]
[7, 3, 7, 4, 8, 0, 4, 0, 3, 7]
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer. Its no possible do it with random module?
Thank you very much. citaret answer works too but I will choose this one because you mention numpy.
No problem @Eduard
3

random.randrange is what you want.

>>> [random.randrange(10) for i in range(5)]
[3, 2, 2, 5, 7]

1 Comment

this is what I was looking for: solve it using core python modules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.