[Tutor] "local variable 'l1' referenced before assignment"
Douglas Drumond
drumond.douglas at gmail.com
Sat Jun 28 07:06:18 CEST 2008
In a2() you do l1 += l2, ie, l1 = l1 + l2
But if you don't have l1 defined yet, you can't add to l2
It's like:
def a2():
l1 = foo + l2
UnboundLocalError: local variable 'foo' referenced before assignment
It's because l1 (and foo at above example) is a local variable.
a1's l1 is different from a2's l1.
On Sat, Jun 28, 2008 at 01:39, Dick Moores <rdm at rcblue.com> wrote:
> I'm puzzled by the below error msg. If I change the line in a2() from
>
> l1 = [1,2,3]*100
>
> to
>
> l1 = [1,2,3]
>
> There is no problem.
>
> Why? And why isn't that line a problem for a1()?
>
> =========================================
> def a1():
> return l1.extend(l2)
> if __name__=='__main__':
> l1 = [1,2,3]*100
> l2 = [4,5,6]
> from timeit import Timer
> t = Timer("a1()", "from __main__ import a1")
> t1 = t.timeit(number=10)
>
>
> def a2():
> l1 += l2
> if __name__=='__main__':
> l1 = [1,2,3]*100
> l2 = [4,5,6]
> from timeit import Timer
> t = Timer("a2()", "from __main__ import a2")
> t2 = t.timeit(number=10)
>
> print "t1:", t1
> print "t2:", t2
> print "t2/t1:", t2/t1
>
> Error msg:
> E:\PythonWork>timing_2_stupidsV2.py
> Traceback (most recent call last):
> File "E:\PythonWork\timing_2_stupidsV2.py", line 21, in <module>
> t2 = t.timeit(number=10)
> File "E:\Python25\lib\timeit.py", line 161, in timeit
> timing = self.inner(it, self.timer)
> File "<timeit-src>", line 6, in inner
> File "E:\PythonWork\timing_2_stupidsV2.py", line 15, in a2
> l1 += l2
> UnboundLocalError: local variable 'l1' referenced before assignment
> ===================================================
>
> Thanks,
>
> Dick Moores
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080628/6c7cec08/attachment-0001.htm>
More information about the Tutor
mailing list