Pick and remove lists from a list through a loop - Python

Hello everyone,

Let me ask my question by a short story! Imagine you have 1000 apples, then you eat 300 of them so you have 700 left. then you eat 300 more so you have 400 then 200 and then final 200. This is a loop But what I want to ask you is that how I can pick and remove these and then keep the remaining items in the list and then pick and remove 300 more and keep the rest?

This is what I did till now:

n = len(cs) ==>
cs is the input name of the component which is in list access and type of 1000 polylines or whatever.

while n > 0:
crvs =
crvs.extend(cs) ==> I imported the in a local list to be able to remove the randomly selected after picking them. Didn’t want to remove the picked ones from the input curve param.

     newcrvs = []
     rnd = rd.sample(crvs, 350)
     newcrvs.append(rnd)

     a = newcrvs (or even rnd itself)

So now I have 650 left. How can I use the rest to random samples from it for 2 or 3 more loops? to pick 300 200 200 from each part?

I hope the story was clear enough. :smiley:

Can anyone help me?

You could do something like this:

import random

apples = list(range(10))  # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
counts = [3, 3, 2, 2]

picked = set()
populations = []

for count in counts:
    if len(picked) + count > len(apples):
        break
    current = []
    while len(current) < count:
        pick = random.choice(apples)
        if pick not in picked:
            current.append(pick)
            picked.add(pick)
    populations.append(current)

print(populations)

# 1st run: [[8, 0, 2], [3, 6, 9], [7, 1], [4, 5]]
# 2nd run: [[7, 0, 8], [5, 9, 1], [6, 2], [3, 4]]
# 3rd run: [[1, 3, 4], [9, 2, 6], [8, 5], [0, 7]]


2 Likes

I might do it this way, just shuffling the list once to reduce the number of function calls:

import random

apples = list(range(10))  # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
counts = [3, 3, 2, 2]
start = 0

picked = apples[:]
random.shuffle(picked)
populations = []

for count in counts:
    populations.append(picked[start:start + count])
    start += count

print(populations)
2 Likes

@diff-arch @Dancergraham Thank you both for your time and help.
Both were very helpful

1 Like