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>As I've learnt that the list comprehensive produces a list (stupid as that might sound :) ) I've added a for loop to iterate over the matchingEmployee list to give the sandwich to whoever wants it.</p>

<pre><code>if matchingEmployee:
print 'Employee(s) found'

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

<p>Thanks</p>

python