Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Loops Loops Loops
#6
(Feb-22-2021, 04:34 PM)snippsat Wrote:
(Feb-22-2021, 01:03 PM)Gilush Wrote: It's my first time reading about the random.sample option. what is the "k" stands for?
random.sample
Basically it picks k unique random elements(sample) from a sequence.
>>> import random
>>> 
>>> random.sample(range(1, 10), 5)
[5, 3, 1, 7, 9]
>>> random.sample(range(1, 10), 5)
[8, 9, 6, 1, 4]
>>> random.sample(range(1, 10), 11)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python39\lib\random.py", line 363, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative
If doing it like this there will not be unique elements.
>>> [random.randint(1, 10) for i in range(5)]
[5, 8, 8, 9, 5]
>>> [random.randint(1, 10) for i in range(5)]
[9, 1, 3, 5, 5]

Thank you.
That answer helps me understand generators better.
Reply


Messages In This Thread
Loops Loops Loops - by Gilush - Feb-22-2021, 12:34 AM
RE: Loops Loops Loops - by deanhystad - Feb-22-2021, 05:24 AM
RE: Loops Loops Loops - by Gilush - Feb-22-2021, 01:03 PM
RE: Loops Loops Loops - by DeaD_EyE - Feb-22-2021, 08:56 AM
RE: Loops Loops Loops - by snippsat - Feb-22-2021, 04:34 PM
RE: Loops Loops Loops - by Gilush - Feb-22-2021, 05:33 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Pyserial issues with proper loops and binary jttolleson 16 2,587 Nov-02-2023, 08:39 PM
Last Post: deanhystad
  for loops break when I call the list I'm looping through Radical 4 881 Sep-18-2023, 07:52 AM
Last Post: buran
  reduce nested for-loops Phaze90 11 1,867 Mar-16-2023, 06:28 PM
Last Post: ndc85430
  Need help with creating dynamic columns with for loops for stock prices PaDat 2 895 Feb-22-2023, 04:34 AM
Last Post: PaDat
  Why both loops don't work in python? nau 3 1,087 Sep-21-2022, 02:17 PM
Last Post: rob101
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,703 Aug-19-2022, 11:07 AM
Last Post: dm222
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,570 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  breaking out of nested loops Skaperen 3 1,212 Jul-18-2022, 12:59 AM
Last Post: Skaperen
  For Loops Driving Me Insane Guybrush3pwood 9 2,203 May-01-2022, 11:01 AM
Last Post: snippsat
  Definitions in User-Created Functions and For Loops new_coder_231013 6 2,088 Dec-29-2021, 05:51 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020