Make All Values In List Different

Hi Everyone,

Haven’t posted in a couple weeks, but I’ve been plugging away with Python. (Maybe `struggling away’ more accurate.)

Anyway, I have code to generate a list of random integers.

Ctr = 0
AlDif = False # Not using `All Different' yet.
NumLst = []
while Ctr < 5:
    NumLst.append (random.randint (1, 9))
    Ctr += 1
print (NumLst)

Output something like [4, 6, 8, 6, 4]

I want to replace the with a different, unique random integer. In the above list, I’d like to replace the second six and the second four.

Now, I can do that by brute force:

If (NumLst [0] == NumLst [1] or NumLst [0] = NumLst [2] …) and so on.

I did exactly that with a list that had only four items and it worked fine. But obviously inefficient. Any suggestions how I might be able to change the duplicates efficiently??

Thank you.

This already exists in the random module :wink:

random.sample(range(1, 10), 5)

If you find this too much like cheating, you could take a look at the code for random.sample:

Hi Sam,

you also could make use of sets as

print( set([4, 6, 8, 6, 4]) )

leads to

{8, 4, 6}

which means, that sets contain every entry just once. Admittedly, the order might be changed by that…

But, there also is a function called shuffle in the random module, so try out the following:

import random
listOfRandoms = list(set([4, 6, 8, 6, 4])) 
random.shuffle(listOfRandoms)
print( listOfRandoms )

The rest should be obvious, right?

Cheers, Dominik

Thanks guys! I don’t consider it cheating to use the tools the language gives us. I just gotta learn how to use them.

1 Like

Also, while others have given you much better solutions for this case, in light of your “brute force” method, I wanted to point out the in operator is equivalent to checking if the object on the LHS is present in the collection (list, tuple, set, etc) on the RHS. To check one element with index i of a list against the rest, you can replace if (NumLst [0] == NumLst [1] or NumLst [0] == NumLst [2] or ... NumLst[0] == NumList[n]) with if NumLst[i] in (NumLst[:i] + NumLst[i + 1:]).

As a minor sidenote, as a matter of universal convention in Python (and the other common languages I know of), there is no space before ( and [ in function calls and slicing, and adding one may confuse others reading your code (as it did me).

Thanks C. A. M.

1 Like