Accessing object from list comprehensive search in Python
<p>I am using a list comprehensive 'search' to match objects of my employee class. I then want to assign a value to them based on who matched the search.</p>

<p>Basically the code equivalent of asking who likes sandwiches and then giving that person a sandwich.</p>

<p>This bit works</p>

<pre><code>class Employee():
  def __init__(self, name, age, favoriteFood):
    self.name = name
    self.age = age
    self.favoriteFood = favoriteFood

  def __repr__(self):
    return "Employee {0}".format(self.name)    

employee1 = Employee('John', 28, 'Pizza')
employee2 = Employee('Kate', 27, 'Sandwiches')

myList = [employee1, employee2]

a = 'Sandwiches'
b = 'Tuna Mayo Sandwich'
matchingEmployee = [x for x in myList if x.favoriteFood == a]

print matchingEmployee
</code></pre>

<p>This prints 'Employee Kate' from the class <strong>repr</strong></p>

<p>The bit I'm stuck on is now giving Kate the Tuna Mayo Sandwich, value b.</p>

<p>I was hoping to do something like </p>

<pre><code>matchingEmployee.food = b
</code></pre>

<p>But this doesn't create a new variable in that object and give it the value b. </p>

<p>Any help would be greatly received. </p>

<p>Since the variable matchingEmployee is a list, and in the given context, Kate is  the first in the list, you can do :   </p>

<pre><code>matchingEmployee[0].food = b 
</code></pre>

python