Question:
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!Answer:
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]
If you have better answer, please add a comment about this, thank you!
Leave a Review