I have a list of class instances Child and I want to modify the toy attribute of each child using the list of toys returned from a function
There is a working solution below but I am wondering if there is a one-liner?
import random
class Child():
def __init__(self, name, toy):
self.name = name
self.toy = toy
def change_toys(nChildren):
toys = ['toy1', 'toy2', 'toy3', 'toy4']
random.shuffle(toys)
return toys[:nChildren]
child_list = [Child('Ngolo', None), Child('Kante', None)]
new_toys = change_toys(len(child_list))
for i in range(len(child_list)):
child_list[i].toy = new_toys[i]
print "%s has toy %s" %(child_list[i].name, child_list[i].toy)
Output (random toy assignement):
Ngolo has toy toy3
Kante has toy toy2
I tried:
[child.toy for child in child_list] = change_toys(nChildren)
But that doesn't work, I get
SyntaxError: can't assign to list comprehension
Any ideas?