Austen Novis
Austen Novis

Reputation: 444

How to set the value inside a list in python?

I have 10 dice that are all programmed the same as D1.

D1 = random.randint(1,12)

I then store them all in a list like this:

roller[DI,D2...]

A person then selects the die to keep (in a while loop) and when he wants to roll the remaining dice he ends the loop. The program below successfully loops, however the dice in the list are not changing. What am I missing?

 while wanted != "11":
        print("The dice left in your roll:" , roller)
        want = int(input("Select Di by using numbers 0-9.")) 
        di = roller[want]
        del roller [want]
        keep.append(di)
        print("Dice that you have kept:" , keep)
        wanted = input("\nType 11 to roll again. Type anything else to select more dice.\n")
        wanted = "12"
        D1 = random.randint(1,12)
        [... more setting ...]
        D10 = random.randint(1,12)

However, after setting the dices D1 through D10, the next iteration of my while loop does not reflect a change of value for the roller list. Why is this?

Upvotes: 0

Views: 267

Answers (1)

brice
brice

Reputation: 25039

Changing D1 won't change the die in the list. You have to change the value in the list itself.

>>> import random
>>> dices = [random.randint(1,12) for i in range(0,10)]
>>> dices
[5, 2, 1, 6, 4, 8, 4, 10, 1, 10]
>>> dices[1] = random.randint(1,12)
>>> dices
[5, 5, 1, 6, 4, 8, 4, 10, 1, 10]

Note above how the second dice (index 1) has changed value in the dices list.

Ie, instead of Dn = random.randint(1,12) where n is your dice, you want to do dices[n] = random.randint(1,12)

More generally, you misunderstand the assignment operator in python.

>>> f = 123

Sets 'f' to point to the value '123'.

If you put f in a list, like this:

>>> my_list = [f, 1, 2, 3]

What you are doing is saying: "create a list, named 'my_list' that has a reference to the value 123, 1, 2 and 3 in it.

When you reassign to 'f', the reference in the list does not change.

>>> f = 456
>>> my_list
[123, 1, 2, 3]

What you're saying is "now f points to the value 456". This does not chnge the meaning of what was put in your list.

[aside]: Interestingly, while this is the case for Python, this is not true of all languages.

Upvotes: 3

Related Questions