I need the following code when executed to produce a list with a fixed length of 4 elements. Why doesn't it work with the for loop?
from random import choice
pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = []
for pulled_ticket in range(4):
pulled_ticket = choice(pool)
if pulled_ticket not in winning_ticket:
winning_ticket.append(pulled_ticket)
print(winning_ticket)
When I execute the code, the results look something like this:
[7, 4, 8, 'e']
[5, 'e']
['e', 6, 3]
But with the while loop, I don't have this problem:
from random import choice
pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = []
while len(winning_ticket) < 4:
pulled_ticket = choice(pool)
if pulled_ticket not in winning_ticket:
winning_ticket.append(pulled_ticket)
print(winning_ticket)
The list length is always four:
['e', 5, 1, 8]
[7, 'd', 2, 8]
[2, 6, 'e', 10]
Thanks a lot!
CodePudding user response:
The answer it pretty logical
when using for pulled_ticket in range(4):
you are going to trigger the choice
and then if
4 times, if you pick the same number twice it will not be added and you will finish with 3 items in the list
the while loop
waits for there to be 4 items so if it gets the same choice multiple times it will just continue
CodePudding user response:
Main issue is like I stated in the comments, Your for loop only always does 4 iterations. While your while loop goes on till the reached length is 4.
Example output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
[4, 8, 'a']
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
[9, 6, 'a', 'b']
You can see that the for loop gives you a 3 size list while doing 4 passes, meaning once it hit the same random number. A way easier way to do this could be so simply use choices, Like @norie, bc you can specify the size of the returning list and there is no need for loops.
print(choices(pool, k=4))
['a', 8, 'd', 8]