Reputation: 29
I'm getting a TypeError saying that the object of type 'int' has no len() when running a while loop on a set.
import random
l = random.sample(range(100), 20)
s = set()
print(s)
print(len(s))
while len(s) < 4:
s = random.choice(l)
I get the right output from the print statements (set()
and 0
) but the aforementioned TypeError when it reaches the while loop.
Upvotes: 0
Views: 161
Reputation: 13106
You need to add the result to the set
, otherwise you are just re-assigning the set
to the result of random.choice
, which is an int
:
while len(s) < 4:
s.add(random.choice(l))
Upvotes: 1
Reputation: 2759
That's because your while
loop is switching the value to an integer at s = random.choice(l)
. See:
import random
l = random.sample(range(100), 20)
s = set()
print(s)
print(len(s))
while len(s) < 4:
s = random.choice(l)
print(s)
this returns:
set()
0
50
and then gives you the type error. So you are getting the error because s
was originally a set, then it gets switched to int
and goes back through the while
loop and has no len
Upvotes: 1