Why work It? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why work It?

I have this code, and work only if I use any(), and I don't know why this don't work without any() a=[0,1] b=[0,1] map(lambda _: a.append(sum(a[-2:])),range(2,10)) any(map(lambda _: b.append(sum(b[-2:])),range(2,10))) print(a) print(b)

22nd Oct 2022, 8:09 PM
Pedro Dominguez
Pedro Dominguez - avatar
1 Answer
+ 4
# Hi, Pedro Dominguez ! # In your code, # map(lambda _: a.append(sum(a[-2:])),range(2,10)) # creates an iterator. When you put any() around it, it will result in that you traverse through the iterator, calling the lambda function each time it iterate. # So map() will just act as a loop and run the lambda function: # lambda _: a.append(sum(a[-2:]) # which create a Fibonacci sequence when the the function is looped. A better approach would be this: def f(n): l = [0, 1] for i in range(2, n): l.append(sum(l[-2:])) return l[:] print(f"{f(10) = }\n") # You can get the same with your map function, but it is not a good approach: a = [0,1] m = map(lambda _: a.append(sum(a[-2:])),range(2,10)) next(m) print(a) next(m) print(a) next(m) print(a) next(m) print(a) next(m) print(a) next(m) print(a) next(m) print(a) next(m) print(a) # and your list a will slowly growe... https://code.sololearn.com/cIG5i23pqfm3/?ref=app
23rd Oct 2022, 6:13 AM
Per Bratthammar
Per Bratthammar - avatar