-3

I want to add a number to an array with its own numbers but want to avoid duplicate numbers

I tried using a for and a while loop but its not working

  • Share your code – Beatdown Mar 27 '23 at 14:27
  • Please add the code you're struggling with to the question – DarkKnight Mar 27 '23 at 14:27
  • Hi @Madpenguin, your question was quickly closed but no worries, this is often the fastest way to be pointed to a good answer for your question! And for some reason stackoverflow is better at finding duplicates after a question has already been posted. If the linked answer is not helpful to you for some reason, please edit your question to make your (incompatible!) requirements clear. – alexis Mar 27 '23 at 14:34

1 Answers1

0

Try something like this:

import random

# Example array
arr = [2, 4, 6, 8, 10]

# Generate a random number that is not in the array
while True:
    num = random.randint(1, 100)  # Choose a random integer between 1 and 100
    if num not in arr:  # Check if the number is not in the array
        break  # Exit the loop if the number is not in the array

# Add the new number to the array
arr.append(num)

print(arr)  # Print the updated array
M K
  • 196
  • 14