0

I was in the process of creating a simple program to generate a password with a 'List' consisting of numbers, symbols, and characters. In the process, I wanted to randomize and shuffle them. I used the random.shuffle method to shuffle the list. My question (Sorry, very new to Python) - why cannot we store the outcome of a shuffle activity into a variable. Giving an example here.

mylist = ["apple", "banana", "cherry"]
shufflefinal = random.shuffle(mylist)

(Why cannot we store the random.shuffle(mylist) into a variable shufflefinal) What is the rule here ? I understand how to get the outcome but wanted to understand the difference and the logic on why this cannot be stored and retrieved through a variable .

Your insight would be valuable .

petezurich
  • 9,280
  • 9
  • 43
  • 57

2 Answers2

3

random.shuffle() function modifies the original list. This function returns None so it can't store modified list to shuffllefinal var.

mylist = ["apple", "banana", "cherry"]
print("Before shuffle: ", mylist)
random.shuffle(mylist)
print("After shuffle: ", mylist)
gajendragarg
  • 471
  • 1
  • 4
  • 11
1

According to the documentation on random.shuffle:

Shuffle the sequence x in place.

This means the list provided as argument is mutated. It follows the same principle as sort, which is also in-place.

If you want to leave the original list unmodified, then create a copy:

mylist = ["apple", "banana", "cherry"]
shufflefinal = mylist[:]  # Get a shallow copy
random.shuffle(shufflefinal)  # Shuffle the copy

The above documentation mentions another way:

To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.

So in your case:

mylist = ["apple", "banana", "cherry"]
shufflefinal = random.sample(mylist, k=len(mylist))
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thanks trincot. I have added another question to make my problem statement better. Sorry for the previous incomplete problem statement. I am very new to StackOverflow posting questions. Pardon me. – venkatforum Feb 14 '22 at 12:43