Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

randomly replace item in list

I have two lists A =[2,3,4,5,33,42,21] and B = [1,11,35,48,19] I want to randomly delete two items of list B and replace with two random items from list A for 200 iteration. I used this code but only one item of B replace with A. how can I do that?

import random

A = [2,3,4,5,33,42,21]
B = [1,11,35,48,19]

x = random.randrange(0,5)
i = A[x]
A[x] = B[x]
B[x] = i
print(A)
print(B)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use random.sample.

import random

list_a = [2, 3, 4, 5, 33, 42, 21]
list_b = [1, 11, 35, 48, 19]

a_index1, a_index2 = random.sample(range(len(list_a)), k=2)
b_index1, b_index2 = random.sample(range(len(list_b)), k=2)
list_a[a_index1], list_b[b_index1] = list_b[b_index1], list_a[a_index1]
list_a[a_index2], list_b[b_index2] = list_b[b_index2], list_a[a_index2]

The only thing needed to be added here is to put it in a loop and loop 200 times.

random.sample chooses k unique choices from an iterable so there won’t be a case where it chooses the same integer twice in an iteration.

If you attempt to use the same index for both list_a and list_b you will never replace the final 2 elements in list_a since list_b is shorter and does not have an equivalent index.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading