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

Shuffling a list without changing the original list

Say that I have a list with elements:

listA = [1, 2, 3, 4, 5]

print(listA) returns:

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

[1, 2, 3, 4, 5]

I want to randomize the elements in listA, but then store this information in listB

import random
listB = random.shuffle(listA)

but if I print listB, it returns None

print(listB)
None

Instead, if I print listA, it returns the randomized list

print(listA)
[3, 2, 1, 4, 5]

What is going on here? How to I re-declare a variable with a new name after applying a function?

>Solution :

You can use random.sample function.

import random

listA = [1, 2, 3, 4, 5] 
listB = random.sample(listA, len(listA))
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