pythonlistshuffle

Pulling a shuffled list index returns the value of the original index


I'm attempting a silly little "random" number generator to try to get to grips with how lists and pulling values from them works in python.

I have a variable defined as x, and I ask the code to pull a value from the list at the index of x. After shuffling the list and asking it to pull the value from index x, it pulls the value from the original list instead of the newly shuffled list.

I'm certain I'm missing something fairly obvious about how the list is shuffled. I originally assumed it's because it's generating a new list upon shuffling instead of actually modifying the original list. However, when printing the original value for list it does show it as the shuffled list and not the original, meaning the original list has actually been modified unless I'm mistaken. I am having a heck of a time troubleshooting this.

import random
numbers = [2, 1, 3, 1, 2]
x = 2 # I plan to import x from a dict with various values 

get_shuffled_number = numbers[x]
print(numbers)
print(get_shuffled_number) #shows the value expected upon print
random.shuffle(numbers) 
print(numbers) #shows the shuffled list
print(get_shuffled_number) #this pulls the original value from the list at index (x) before being shuffled

gets the output

[2, 1, 3, 1, 2]
3
[1, 2, 2, 3, 1]
3

so numbers[x] is pulling the index of 2 from the original list and not the shuffled list after being shuffled.


Solution

  • Code review time.

    numbers = [2, 1, 3, 1, 2]
    x = 2
    

    Ok, good. (I might have opted for index i = 2, but fine, whatever, LGTM.)

    get_shuffled_number = numbers[x]
    

    This is just Wrong. We choose a verb when naming a def get_shuffled_number(...): function, and we choose a noun for such an assignment. So prefer to assign shuffled_number = ....

    Choosing the wrong name affects how you and your colleagues reason about the code. And not in a good way.

    What you wanted to do was

    But you didn't do that. You assigned the variable exactly once, before the shuffle, so understandably it never changed thereafter.


    As a separate item, you chose three distinct values for a 5-element list. Prefer to populate that list with five distinct values. Even then, please understand that after a shuffle() you would still have a 20% chance of the selected number being unchanged. Use a longer list of distinct values if you wish to reduce that likelihood.