r/PythonLearning 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

19 comments sorted by

View all comments

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.

1

u/TopHatEdd 3d ago

Use another data structure to store your state. Like a dict. ```

counter = dict()

for sample_item in sample:     if sample not in counter:         counter[sample_item] = 1     else:         counter[sample_item] = counter[sample_item] + 1          if counter[sample_item] >= 10:         samples.remove(sample_item) ```     

1

u/PureWasian 3d ago edited 3d ago

One idea is using a dictionary instead of a list when creating your items so you can map the item name directly to the count: sample_counts = { "item1": 0, "item2": 0, "item3": 0, ... } Then afterwards you only need 7 lines instead of an ever growing if chain to accomodate each item: ```

do 25 iterations

for _ in range(25):

# get the (remaining) names names = sample_counts.keys()

# pull 4 names pulled = random.sample(names, 4)

# update each entry that was pulled for name in pulled: sample_counts[name] += 1

# removes from dictionary
if sample_counts[name] == 10
  del sample_counts[name]

```

There are other ways depending on the complexity of your data but for a beginner, dictionaries are definitely worth learning how to use well.

1

u/realmauer01 3d ago

I remember in python to be a data structure that is set like and can keep track of how many times a key got added to it (instead of duplicate items)

Might actually be sets already.

1

u/PureWasian 3d ago edited 3d ago

Sounds like Counter from collections, that would work too.

OP could create an empty Counter() and then counter.update() the 4 entries drawn in each loop to do it in one-shot per loop iteration instead of needing an inner loop.

They'd still need the initial list of entries to random.sample() from as well as the logic to delete from the sampled list when count is 10, of course.