skribe,
@skribe@aus.social avatar

Python folks: in random.choices, does it always return the k value of choices? ie.

names = random.choices(names_list, k=20)

It would return 20 random names from names_list (including duplicates). What if there's not enough names in names_list?

I have some code that regularly returns less. I'm trying to determine if it's a Django problem. Similar (non-Django) code doesn't have this issue, hence my confusion.

bmispelon,
@bmispelon@mastodon.social avatar

@skribe according to the docs, random.choices is with replacement, which should mean you'll always get k elements, possibly with duplicates (or guaranteed duplicates if k>len(choices) )

Or if choices is empty, you'll get an exception (IndexError)

bmispelon,
@bmispelon@mastodon.social avatar

@skribe (the random module is written in Python, so you can check how random.choices is implemented: https://github.com/python/cpython/blob/3.12/Lib/random.py#L454).

Which Django code are you using that returns less choices?

skribe,
@skribe@aus.social avatar

@bmispelon thanks for the reply.

The only relevant part of Django I'm using is generating the names list from a database via a form. The list appears to be properly populated from the database, but when k is set to 10+ it doesn't always produce the correct number of names. It also doesn't produce duplicates... Well...

Ok, short story. The code is used to produce a first name and a surname. I produce them individually (similar code from the same form). They're zipped together for output.

The really weird part: the first names are never duplicated. Surnames sometimes are. I have about 200 each of first names and surnames in the db.

I hate bugs like this.

bmispelon,
@bmispelon@mastodon.social avatar

@skribe that is weird indeed 🤔

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • DreamBathrooms
  • mdbf
  • ngwrru68w68
  • magazineikmin
  • thenastyranch
  • rosin
  • khanakhh
  • osvaldo12
  • Youngstown
  • slotface
  • Durango
  • kavyap
  • InstantRegret
  • GTA5RPClips
  • provamag3
  • ethstaker
  • cisconetworking
  • tester
  • modclub
  • everett
  • cubers
  • tacticalgear
  • Leos
  • megavids
  • normalnudes
  • anitta
  • JUstTest
  • lostlight
  • All magazines