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>Use the command line python to write a simplified expression:</p>

<pre><code>[ y for y in [1,2,3,4] if y %2 ==0]
</code></pre>

<p>You will see that it results in a list output</p>

<pre><code>[2, 4]
</code></pre>

<p>Your "matchingEmployee"  is actually a list of matching employees.  So to "give a sandwich" to the first employee found (assuming there is one):</p>

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

<p>To "give a sandwich" to the list of employees:</p>

<pre><code>for employee in matchingEmployee:
    employee.food = b
</code></pre>

python