Home > Software design >  How do I fix an "'int' object is not iterable" error in list function?
How do I fix an "'int' object is not iterable" error in list function?

Time:08-29

Here's my code:

from random import random
for i in range(100):
  a = list(int(random() * 100))
  print(a)

and I keep getting this error message:

TypeError: 'int' object is not iterable

What am I doing wrong? Please help me.

CodePudding user response:

In order to generate a list of 100 random numbers between 0 and 99, you'll have to either create the list first:

from random import random

a = []
for _ in range(100):
    a.append(int(random() * 100))

or use a list comprehension:

from random import random

a = [int(random() * 100) for _ in range(100)]

CodePudding user response:

You haven't shown your expected output, but I presume you're looking for

from random import random
for i in range(100):
  a = [int(random() * 100)]
  print(a)

CodePudding user response:

You are trying to convert a type int to type list, which cannot be done. If you want to add your random number multiplied by 100 you can do the following.

from random import random
random_numbers = []
for i in range(100):
  random_numbers.append(int(random() * 100))

CodePudding user response:

I'm trying to take 100 random numbers in a list.

You need to create a list and append the generated random numbers into it:

import random

a = []
for i in range(100):
    a.append(int(random.random() * 100))
print(a)

Note that you can also simply use random.randint:
(use random.randrange(0, 100) or random.randint(0, 99) if you don't want to include 100 as a possibility)

import random

a = []
for i in range(100):
    a.append(random.randint(0, 100))
print(a)

And you can simplify the whole thing by using a list comprehension:

import random

a = [random.randint(0, 100) for __ in range(100)]
print(a)

(Using __ here as an ignored variable.)

CodePudding user response:

we can use random.sample(...) to get the numbers. sample() has 2 arguments: population or iterable, k= defines the number of samples we wanted to get.

sample() does not create duplicates! if duplicates are allowed, we can also use choices() instead.

from random import sample
nums = list(map(lambda x: x * 100,sample(range(100), k=100)))
print(nums)
  • Related