Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introducing Lists Meet Lists Addition

+= operator for list concatenation instead?

I was playing with the REPL and I discovered you can extend lists using the += operator as well. Is there any detriment to doing this? Any unexpected bugs I could run into in the future?

1 Answer

Steven Parker
Steven Parker
229,732 Points

You cannot use the compounding assignment operator on a non-local variable (one that is not local to a function and also not global):

def test():
    nonloc = [1, 2, 3]

    def extendit():
        nonloc.extend([4])

    def compoundit():
        nonloc += [5]

    extendit()    # this will work
    compoundit()  # but this will fail

test()

You'll get an "UnboundLocalError" (local variable referenced before assignment).

Ah, I see. So if I'm understanding this correctly, the scope of the compounding assignment operator is only within a code block. Could you explain why?

Steven Parker
Steven Parker
229,732 Points

It's not a scope issue, it has to do with how the system accesses the references. With that operator it appears that you are attempting to reference a new variable before it is created.

The intended variable is actually available to the function, but you have to declare it before accessing it:

    def compoundit():
        nonlocal nonloc  # adding this declaration will make it work
        nonloc += [5]

But the point is that you don't encounter these complications when using "extend".