2

So, in this code, I'm trying to make list_1 a list of 8 strings from alp_list where no strings are the same, and to delete the items in list_1 from alp_list for more codes. I'm not sure what's the best way to do this.

import random

alp_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
a = 0
list_1 = []
while a < 9:
    random_alp = random.choices(alp_list)
    list_1.append(random_alp)
    alp_list.remove(random_alp)
    a += 1
print (list_1)
2
  • Just a small point, if you choose to stay with this kind of loop: instead of using a counter (which most Pythonistas try to avoid at all costs), you can say something like while len(list_1) < 9. Commented Feb 11, 2022 at 0:43
  • 1
    Just as another option to consider, what you're doing is very similar to shuffling and dealing from a deck of cards. You could do random.shuffle(alp_list), and then just pull items from the top using .pop(0) or by slicing (alp_list[:9]). Commented Feb 11, 2022 at 0:56

1 Answer 1

3

You may use a preexisting function:

list_1 = random.sample(alp_list, 8)

To delete the items from the original list, you may go with:

for item in list_1:
    alp_list.remove(item)
Sign up to request clarification or add additional context in comments.

1 Comment

It's convenient for sure, but they also want to remove from the original list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.