Generate a unique number for each entry

Started learning Python yesterday; I know little more than what is here, below.

The random generator functions but the same number applies to each entry.

Could someone show me how to generate a unique number for each entry (one, two, three)?

Thank you.

Code so far:

import random

number_gen = random.choice(range(100))
num = str(number_gen)

for group in ("Group_A:", "Group_B:"):
	print(group)
	print("  one", num)
	print("  two", num)
	print("  three", num)
	print()

This means, choose a number right now, and remember it. It does not mean “every time we use this variable, do the calculation again”.

If you need more random numbers, then you need to call it more times. For example, by calling it at the point where you need it.

Incidentally, you should learn the basic techniques for string formatting:

Thank you, it’s all confusing to me, but it’ll get easier the more I do, of course.

I did call it at the points I needed it.

Note that just calling random.choice multiple times does not ensure that you will get different values each time.

Calling means using the () at the end, like when you called str in num = str(number_gen). You can create your own function that creates a random number, then call it whenever you need one.

>>> from random import randint
>>> help(randint)
Help on method randint in module random:

randint(a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.
# this just saves having to use choice(range())
>>> def num():
...  return randint(1,10)
...
>>> for x in ('a', 'b', 'c'):
...  print(x, num())
...
a 3
b 2
c 5

Well that’s completely obvious by the fact I stated that’s the problem, in my OP - I already knew that.

A function from the random module that is designed to produce random sample without replacement is random.sample.

So, you could do

values = random.sample(range(100), k=6)

for i, group in enumerate("Group_A:", "Group_B:"):
    print(group)
    print("  one", values[i + 0])
    print("  two", values[i + 1])
    print("  three", values[i + 1])
    print()

That certainly provides the result. Now I have to work through it to understand it.

Thank you, much appreciated.

And, for the record, this is for personal use, not for school; I’m nearly 60, not schoolage - just in case anyone’s wondering.

Thanks, again.

I’m sure you mean well, but that is gibberish to me - again, I started learning Python yesterday; I have no idea what that all means.

Thanks, but we can end the conversation here before there’s more confusing information.

It really depends on what you need but the random package is not a good goto. Thats for random generation, not unique number generation.

import uuid
uuid.uuid4().int

this will give you a unique integer each time it is run. This number is universally unique so in theory its unique to your machine at the time of execution so the chance of collision is infinitesimally small

That being said this number is going to be VERY big. It really depends on what your uniqueness needs are. If you simply need a number which is unique per session you can have an incrementing counter

__counter = 0
def get_next_int_id():
     global __counter
     __counter +=1
     return __counter

This will give you a id that will always be unique on this run of your program.

1 Like

How’s that materially different? It’s still a random number.

they wanted a unique number not a random number those are different things.

uuid4 doesn’t guarantee uniqueness.

be more specific about what level of uniqueness your referring to.

No, YOU be more specific about how uuid4 is better than random. You necro’d a thread to tell people to avoid the random module. Without good justification, that’s FUD and has no value to anyone.

The reason to use uuid over random is that it handles correctly seeding the generator and ensuring that you have a wide enough keyspace to provide a sufficient level of randomness that in the majority of practical use cases you should never experience a collision.

I asked you what level of uniqueness you were referring to is I wanted to understand your position, you made a very dogmatic assertion and I wanted to make sure I wasn’t missing something. I’m really not sure why your bringing out the guns here and throwing about insults, If I’m wrong here correct me with something specific, that way atleast there is benifit.

More baseless FUD. The random module seeds the generator correctly, and uses a Mersenne twister with a period of 2**19937-1 which is a lot more than you’ll need for most purposes.

YOU started with the dogmatic assertion that the random module “is not a good goto”. You started out by making a bold claim with no basis.

Probably what you’re missing is that Python’s random module is a lot better than you’re giving it credit for?

It’s not FUD, That requires deliberate malicious intent, I’m repeating what I’ve been taught and I’m thinking I’ve been mislead.

How would you approach this using random?

You are spreading FUD and I’m calling it like it is. If you repeat what you were told without checking it, then you may not have invented it, but it’s still causing the same problems. Remember, Python doesn’t ship bad modules just to mess with people. Think before you post - why would Python include a bad random module?

Probably just random.randrange(some_big_number) if I want randomly generated IDs. They’ll usually be good enough, and certainly they’ll be no worse than UUID4 if you pick a number that’s 2**128 or higher. But if I actually care about uniqueness, I have a central broker - usually a database - that checks them. Otherwise, anything that generates randomly is about as good as anything else that generates randomly, with the chance of collisions, so I would just use the simplest and most obvious: the random module.

2 Likes

While unlikely, it’s possible for the Mersenne Twister to fall into states where it gets the same 32-bit output hundreds of times in a row.

A much simpler solution to get unique ints:

>>> import itertools
>>> getid = itertools.count().__next__
>>> getid()
0
>>> getid()
1
>>> getid()
2
>>> getid()
3

This is thread-safe too, although not multiprocessing-safe. Over the life of a process run, it will always return a unique int.

3 Likes