johnbeatty02
johnbeatty02

Reputation: 83

Unable to index in Python

I am trying to locate a random value from one array in another array:

team1Players = random.sample(activePlayers, 4)
print(team1Players[0])
index1 = overallPoints.index(f'{team1Players[0]}')

The above code yields the following output:

/Users/johnbeatty/PycharmProjects/THTTeamMakerv2/venv/bin/python /Users/johnbeatty/PycharmProjects/THTTeamMakerv2/main.py
playerName 
Traceback (most recent call last):
  File "/Users/johnbeatty/PycharmProjects/THTTeamMakerv2/main.py", line 237, in <module>
    index1 = overallPoints.index(f'{team1Players[0]}')
ValueError: 'playerName' is not in list

Process finished with exit code 1

I do not see why there should be a problem here; Python clearly recognizes the playerName and its name in the list... Would anybody be able to help me out here?

Upvotes: 1

Views: 55

Answers (2)

Mustafa Khan
Mustafa Khan

Reputation: 46

The issue in this line: overallPoints.index(f'{team1Players[0]}' is that you are trying to search for a player name in overallPoints, which is a list of tuples. You won't find any player names by themselves there. You will only find tuples.

Try this instead:

import random 

activePlayers = ["Jack", "Ken", "Kyle", "Donald", "Amy"]
overallPoints = [("Jack", 10), ("Ken", 15), ("Kyle", 20), ("Donald", 30), 
("Amy", 40)]

team1Players = random.sample(activePlayers, 4)
index1 = [i[0] for i in overallPoints].index(team1Players[0])
print(team1Players)

Some additional notes:

  • If you are concerned about the speed or complexity of the proposed approach, look through this related stackoverflow post for other suggestions on how to use the .index() function when parsing a list of tuples.
  • I used the fake data above when testing my approach since activePlayers and overallPoints was not provided.
  • I assumed that a player from activePlayers would always be present in one of the tuples in overallPoints.
  • I assumed that player names are unique. If this is not true and the sampled player from activePlayer has the same name as another player that exists in activePlayer, then the program as is will only return the index of the first appearance of the player in overallPoints.

Upvotes: 3

Haneen
Haneen

Reputation: 1146

It's because overallPoints array does not have a value 'playerName'.

You should add the value inside overallPoints.

Upvotes: 0

Related Questions