0

I want to loop over a list of strings and construct different functions with each string. It looks like references to the string variable are being stored. So when I call each of the foo functions they each only use the last assignment to s. Is there a different way to achieve this?

los = ['hello', 'and', 'bye']
foos = []
for s in los:
    k = s
    def foo_():
        print k
    foos.append(foo_)

for i in foos:
    i()

prints

bye
bye
bye
chew socks
  • 1,346
  • 2
  • 15
  • 34

0 Answers0