Python Forum
Generate unique random numbers from different lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generate unique random numbers from different lists
#1
Hi Guys,

My objective is to select 5 unique random numbers from a range of numbers inside a list, prior to storing them inside a final list. These 5 random numbers shall not be numbers from another list. However, my code below doesn't have the desired outcome that I want to achieve. Please advise me based on my code below. Thank you in advance.

import random

# The "outcast_list" list contains numbers to be filtered off.
outcast_list = [1, 2, 3, 4, 5]

# The "whole_list" list contains numbers that the generated number shall randomly choose from.
whole_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

selection_list = []
status = False

# Create a loop until the "status" turns True (i.e. when the list of randomized numbers has 5 numbers inside it.).
while status is False:
	# Generate one random from the "whole_list" one at a time.
	i = random.sample(whole_list, 1)

	# Create the following 3 conditions before adding the number into the "selection_list" list.
	if (i not in outcast_list) and (i not in selection_list) and (status is False):
		selection_list.append(i)

	# Break out of the "while" loop when the "selection_list" has 5 numbers inside it.
	if len(selection_list) == 5:
		status = True
		break

print(selection_list)

# Execution outcome: [[10], [3], [8], [4], [7]]
# Desired outcome: [6, 7, 8, 9, 10]
Reply


Messages In This Thread
Generate unique random numbers from different lists - by Takeshio - May-24-2019, 04:32 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  random numbers, randint janeik 2 647 Nov-27-2023, 05:17 PM
Last Post: janeik
  Sample random, unique string pairs from a list without repetitions walterwhite 1 553 Nov-19-2023, 10:07 PM
Last Post: deanhystad
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,566 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Generate lists of devices and partitions from /proc/partitions? DachshundDigital 1 831 Feb-28-2023, 10:55 PM
Last Post: deanhystad
  List of random numbers astral_travel 17 2,903 Dec-02-2022, 10:37 PM
Last Post: deanhystad
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,668 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Generate random id (please help!) Kjaglewicz 8 2,142 Aug-29-2022, 09:37 AM
Last Post: fracjackmac
  generating random string unique forever Skaperen 5 2,438 Aug-20-2021, 07:15 AM
Last Post: Gribouillis
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,932 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  Generate random hex number ZYSIA 1 12,019 Jul-16-2021, 09:21 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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