Reputation: 155
I am making a program where it generates a random number from 1 to 100 and then, if that number isn't already in the list, it adds it to the list and keeps doing that until there is 100 unique numbers in the list. This is my code so far:
from random import randint
numbers = []
loop = True
while loop == True:
number = randint(1, 100)
if number in numbers:
print("{} is there already!".format(number))
else:
numbers += number
But it keeps giving me this error:
Traceback (most recent call last):
File "main.py", line 9, in <module>
numbers += number
TypeError: 'int' object is not iterable
But, as I'm pretty sure, there's nothing wrong with my code. What do I do?
Upvotes: 1
Views: 720
Reputation: 113
I think you are trying to add random numbers from 1-100, randomly in numbers list and you don't want to add anything more than once
from random import randint
numbers = []
loop = True
while loop == True:
number = randint(1, 100)
if number in numbers:
print("{} is there already!".format(number))
else:
numbers += [number]
This will do.
I think you should use append instead of adding, because it takes much less time. It will look like this
from random import randint
numbers = []
loop = True
while loop == True:
number = randint(1, 100)
if number in numbers:
print("{} is there already!".format(number))
else:
numbers.append(number)
Upvotes: 1
Reputation: 3856
If you just want to create a shuffled list with unique numbers from 1 to 100
This can be a more efficient code
my_list = list(range(1,101))
random.shuffle(my_list)
print(my_list)
You can fix the random seed so the output is shuffled but doesn't change every time you run
my_list = list(range(1,101))
random.seed(123)
random.shuffle(my_list, random=None)
print(my_list)
As for your code, you cannot do +=
for a list use .append
(which takes your number as an argument and adds that to end of your list)
numbers.append(number)
DOCS: https://docs.python.org/2/tutorial/datastructures.html
Upvotes: 1