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

Enzo Cnop
Enzo Cnop
5,157 Points

Practical difference between using "+" to append a list and "+="

In practice, what is the difference between using the 'temporary' modifier of a list '+' and the 'permanent' modifier '+='. Obviously one is temporary and one is permanent, but those terms are rather subjective. When does Python decide to forget a temporary list change? How could this be used to my advantage?

Jack Gerrard
Jack Gerrard
1,322 Points

Hello,

I haven't done python for a long time so there might well be a better answer than mine,

in short += is a replacement for x=x+y where as + is simply x+y

using arrays is a bit more complicated and depends entirely on the place it is used during your code, if it is contained within a function the value is manipulated inside that function and the value could be returned with the return keyword,

if not within a function it will have a bigger effect.

This will be made more clear when you get on to studying object oriented programming and the term encapsulation makes more sense to you.

1 Answer

Steven Parker
Steven Parker
229,644 Points

The "+=" is an addition assignment operator.

It basically combines addition and assignment at the same time. As Jack mentioned, "x += y" is essentially the same as "x = x + y". Both of these are types of assignments, so they permanently change the item on the left.