Well, actually, not that much harder. Now that we know how to define functions, we could define len ourselves if it did not exist. Previously, we have used the accumlator pattern to count the number of lines in a file. Letβs use that same idea and just wrap it in a function definition. Weβll call it mylen to distinguish it from the real len which already exists. We actually could call it len, but that wouldnβt be a very good idea, because it would replace the original len function, and our implementation may not be a very good one.
Rearrange the code statements to match the activecode window above. (This is an exercise in noticing where the indenting and outdenting happens, and where the return statement goes.)
def mylen(x):
---
c = 0 # initialize count variable to 0
---
for y in x:
---
c = c + 1 # increment the counter for each item in x
---
return c
---
print(mylen("hello"))
print(mylen([1, 2, 7]))