-3

How can I use python to check if a object in my list already contains the same name?

  • Class Object Team
    • attribute: name

I have a list which contains multiple 'Teams'

pseudo code

teams = [Team name="Dolphins", Team name="Browns", Team name="Ravens"]

How can i test if the team 'Browns' already exists? Is it just a simple for-loop going item by item, or does python have some shortcode to do this?

JokerMartini
  • 5,674
  • 9
  • 83
  • 193
  • 1
    `if 'Dolphins' in teams'` EDIT: sorry i thought they were just simple strings. is it a class with the attribute name? – R Nar Oct 30 '15 at 17:46
  • "I have a list..." That does not look like a Python list to me. It gives me `SyntaxError` when I run it. Do you mean you have a text file which your script is reading? – Kevin Oct 30 '15 at 17:47
  • correct. its a class with attribute 'name' – JokerMartini Oct 30 '15 at 17:49
  • http://stackoverflow.com/questions/7125467/find-object-in-list-that-has-attribute-equal-to-some-value-that-meets-any-condi – R Nar Oct 30 '15 at 17:50
  • I'm confused. Which is it? A text file or a class? Classes usually start with `class ClassName:`, which you don't have. – Kevin Oct 30 '15 at 17:52

2 Answers2

2

If the team name is what defines equality, you can do something like this:

class Team(object):
    def __eq__(self, other_team):
        return self.name == other_team.name

And then you can simply do if team in teams (where team is an instance of Team and teams is a list of instances of Team).

Demian Brecht
  • 21,135
  • 5
  • 42
  • 46
0

The list looks not pythony, but if we assume it is, then here is the way:

class Team:
    def __init__(self, name):
        self.name = name

teams = [Team("Dolphins"), Team("Browns"), Team("Ravens")]

def checkIfNameExists(team_obj_list, the_name):
    for team in team_obj_list:
        if (team.name == the_name):
            return "Name " + the_name + " already exists"

print checkIfNameExists(teams, "Browns")
Vadim
  • 633
  • 1
  • 8
  • 17