a += b is not always a = a + b

Course Curriculum

a += b is not always a = a + b

a += b is not always a = a + b

In python a += b doesn’t always behave the same way as a = a + b, same operands may give the different results under different conditions.

Consider these examples for list manipulation:
Example 1

list_1 = [5, 4, 3, 2, 1]
list2 = list_1
list_1 += [1, 2, 3, 4]

print(list_1)
print(list2)
Output:

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1, 1, 2, 3, 4]

Example 2

list_1 = [5, 4, 3, 2, 1]
list2 = list_1
list_1 = list_1 + [1, 2, 3, 4]

# Contents of list_1 are same as above
# program, but contents of list2 are
# different.
print(list_1)
print(list2)
Output:

[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1]

Logic Gates in Python (Prev Lesson)
(Next Lesson) Difference between == and is operator in Python
', { 'anonymize_ip': true });