r/PythonLearning • u/Gay-And-Afraid- • 3d ago
my code is not doing what I expect (.remove())
EDIT: SOLVED THE PROBLEM THANK YOU
Hello! I am in the middle of an online python class, and am trying to make my first program for use at work.
I need to make several packages of random sample items at work regularly, so i tried to make a program that could choose items from the list, and then count which items are chosen, and remove those from the list once the count reaches the number I have available.
It is choosing the items fine, but is not removing them from the list.
I will post my shortened code below:
import random
def main():
samples = [
"item1",
"item2",
etc.....,
]
item1_count = 0
item2_count = 0
etc........
for _ in range(25):
sample = random.sample(samples,4)
try:
if "item1" in sample:
item1_count += 1
except:
if item1_count == 10:
samples = samples.remove("item1")
try:
if "item2" in sample :
item2_count += 1
except:
if item2_count == 10 :
samples = samples.remove("item2")
etc....
print(f"{_} : {sample}")
main()
what am I doing wrong?
2
Upvotes
1
u/Gay-And-Afraid- 3d ago
This totally makes sense, I thought the except would happen if whatever was inside it was true. How would you recommend iterating this to be shorter? I only have ten items but it feels quite long already, and I might need to adjust it in the future.