Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
221,322 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.