I made a very simple function that takes a list of numbers and returns a list of numbers rounded by some digits:
def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(round(i, digits))
return neulist
However, I mistakenly put the function itself in the code instead of the built-in round()
(as in the example below):
def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(rounded(i, digits))
return neulist
and got this output:
Traceback (most recent call last):
File "<pyshell#286>", line 1, in <module>
rounded(a)
File "<pyshell#284>", line 4, in rounded
neulist.append(rounded(i, digits))
File "<pyshell#284>", line 3, in rounded
for i in lista:
TypeError: 'float' object is not iterable
The question is: how does the interpreter know that it had to apply the function rounded()
while evaluating the function rounded()
itself? How can it anyway now that rounded()
is a function taking floats if it is attempting to interpret that very function? Is there a sort of two cycle procedure to evaluate & interpret functions? Or am I getting something wrong here?
The function is an object. It is created at definition, not when it is called, so if Python didn't know how to use it, it would've raised an error before any calling was done.
However, you called it with a list. During the iteration, the function is called recursively with the first item of the list - presumably, a float. With this float as argument,
for i in lista:
doesn't make sense anymore, and you have the error.