I have a dictionary defined say D, I also have initialized it.

When I say len(D), some time it gives me correct answer, but some times it throws me error saying

UnboundLocalError: local variable 'len' referenced before assignment

can anybody tell me why is this error. Am I wrong some where.

Thank you,
kath.

hmm, are you using 'len' as a variable anywhere else in your program?
Check to see if you are using 'len' as a variable in your program, because thats where i get the error:

dic = {1:1,2:2,3:3,4:4}

print len(dic)

def main():
    print len(dic)
    len = len(dic)

if __name__ == '__main__':
    main()

and the output:

>>>
4

Traceback (most recent call last):
File "C:/Python25/testDICTS.py", line 10, in <module>
main()
File "C:/Python25/testDICTS.py", line 6, in main
print len(dic)
UnboundLocalError: local variable 'len' referenced before assignment

Tis a funny error though, i never did work it out, i just changed my code till i didn't get it, hehe if that doesn't work then i don't know, sorry

happy coding
a1eio

Smart observation a1eio!
Using Python's builtin function names for a variable name seems to trip plenty of new programmers. I got tripped on str when I started writing Python code. Module names can also trip you up!

Use the following to check for names you want to avoid ...

help("__builtin__")
help("modules")

I have a habit to add a 1 (or a 2 and so on) behind the name, like str1, str2, list7 or len1 to make them somewhat unique.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.