Purpose of "+ \", "+="


#1

Hi everybody,

Maybe i skip the section or don't remember what describe this operator.i don' t get it's purpose and usage.

Could anybody share the link of lessons teach this operator.

I.e

cost = {
"apples": [3.5, 2.4, 2.3],
"bananas": [1.2, 1.8],
}

return 0.9 * average(cost["apples"]) + \
0.1 * average(cost["bananas"])

How does work the "+ \" ?


#2

Hi @pinkamoeba ,

The += operator is an enhanced assignment operator. This statement ...

x = x + 1

... is equivalent to ...

x += 1

However in this code...

return 0.9 * average(cost["apples"]) + \
0.1 * average(cost["bananas"])

... the \ is a line continuation character that enables statements to span more than one line.


#3

thank you so much man


#4

This might just be confusing, and not exactly high priority to learn.
But += is not totally equivalent to addition and assignment

For mutable values += and other compound statements are actually meant to mutate (change/modify) the object itself instead of creating a new one.

For example, [1] + [1] creates a third list, while

a = [1]
a += [1]

doesn't create a third list but instead modifies the one that a refers to.

Some code that demonstrates this:

a = [1]
b = [2]
print a + b # [1, 2]
print a # [1]
print b # [2]

a = [1]
b = [2]
c = a # c now refers to the very same list as a, it's not a copy
a += b
print c # [1, 2]