0

I am trying to loop through two elements in a list (integers) and for each element in the list if the value is equal to the integer, I want to replace the element with the string. What am I doing wrong?

players = [np.random.randint(1, 4), np.random.randint(1, 4)]

for i in players:
    if i == 1:
        players[i] = 'rock'
    elif i == 2:
        players[i] = 'scissors'
    elif i == 3:
        players[i] = 'paper'

player_1 = players[0]
computer = players[1]

print(player_1)
print(computer)
Actual:

scissors
1

or, I get this error:

Traceback (most recent call last):
enter Player 1's choice:
  File "...", line 12, in <module>
    players[i] = 'scissors'
enter Player 2's choice:
IndexError: list assignment index out of range


Expected

scissors
rock
1
  • i is not the index it is actually the element inside the list. try enumerate or simply use range(len(players)) rather than players Commented Aug 9, 2019 at 18:57

3 Answers 3

1

i is returning a value between 1 and 4, that's why you have the list assignment index out of range error.

And you can just make a list of items:

items = ["rock","scissors","paper"]

and select them randomly

players = [items[np.random.randint(1, 4)], items[np.random.randint(1, 4)]]
Sign up to request clarification or add additional context in comments.

Comments

0

i is the value of that element in the list, not the index. If you want to change the list than iterate using indices.

for indx, val in enumerate(players):
    if val == 1:
        players[indx] = 'rock'
    elif val == 2:
        players[indx] = 'scissors'
    elif val == 3:
        players[indx] = 'paper'

Also you don't need to use a large package like NumPy to get some random numbers since python has a built in way to do it:

import random
choices = [random.randint(0, 2) for _ in range(2)]
print(choices) # [0, 2]

You also can just use random to its fullest:

import random
CHOICES = ('rock', 'paper', 'scissors')
choice1 = random.choice(CHOICES)
choice2 = random.choice(CHOICES)
print(choice1, choice2) # rock paper

Comments

0

Use len property of the list to iterate

for i in range(len(players)):
    if players[i] == 1:
        players[i] = 'rock'
    elif players[i] == 2:
        players[i] = 'scissors'
    elif players[i] == 3:
        players[i] = 'paper'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.