Addition, Concatenation, and Increment
Many Python learners consider addition and increment to be similar or even the same, like
a = a + 1 is basically the same as
a += 1. Here are some examples to show you that they’re actually not — when “addition” is actually “concatenation.”
To start off, let’s use the increment operator
+= to add a name to a roster:
name1 = "Alex" roster1 = ["Mary", "Brenda", "Celine"] print("The ID of roster1 is", id(roster1)) roster1 += name1 print(roster1) print("The ID of roster1 is", id(roster1))
# OUTPUT The ID of roster1 is 4366329024 ['Mary', 'Brenda', 'Celine', 'A', 'l', 'e', 'x'] The ID of roster1 is 4366329024
Note that the string value
“Alex” is broken into four characters
‘A’, ‘l’, ‘e’, ‘x’ before added to the
roster1 list. If you want
“Alex” to be appended as a whole, you should assign a list (
[“Alex”]) or a tuple (
“Alex”, — side note:
(“Alex”) is still a string, but
(“Alex”,) is a tuple!) to the variable
name1 is a string, list, or tuple, the increment operator works like a charm. Of course, you can also “append” the tuple
name1 to a tuple named
roster2, but you should know that, despite the same variable name
roster2, a new tuple with a new ID will be automatically created since tuples are immutable. On the other hand, appending a new member to a list will not alter the ID of that list since lists are mutable.
name1 = "Alex", roster2 = ("Jim", "Peter", "Mark") print("The ID of roster2 is", id(roster2)) roster2 += name1 print(roster2) print("The ID of roster2 is", id(roster2))
# OUTPUT The ID of roster2 is 4305622592 ('Jim', 'Peter', 'Mark', 'Alex') The ID of roster2 is 4305580288
But what if we replaced the increment operation with a regular addition?
name1 = "Alex" roster1 = ["Mary", "Brenda", "Celine"] roster1 = roster1 + name1 print(roster1)
Dang, we’ve got an error this time:
# OUTPUT roster1 = roster1 + name1 TypeError: can only concatenate list (not "str") to list
+ means concatenation, you’re expected to concatenate values of the same type — that is, two (or more) strings, OR two (or more) lists, OR two (or more) tuples. Elements of different types cannot be concatenated — even not NoneType!
But with an increment operation, the limit seems to be lifted a bit. While still limited to augmenting a tuple with another tuple or a string with another string, you can choose to extend a list with a list, a tuple, or more weirdly, individual characters extracted from a string.
How about adding integers to these data structures?
num1 = 5 roster1 = ["Mary", "Brenda", "Celine"] roster1 += num1 print(roster1)
We’ve got a TypeError again:
# OUTPUT roster1 += num1 TypeError: 'int' object is not iterable
This is because mathematical operation can only happen between numerical values (integers and floats). But if we put the integer
5 into a list or tuple, the issue is gone:
num1 = 5, roster1 = ["Mary", "Brenda", "Celine"] roster1 += num1 print(roster1)
# OUTPUT ['Mary', 'Brenda', 'Celine', 5]
A roundup of the above, and more…Group A:
+can be used to add up numbers (integers and/or floats);
+can be used to concatenate data structures of the same type (mixed types must be avoided; remember that con- means together or common). Minimal units of the two data structures will be stitched together without anything in between. The updated data structure will be of the same type as the two;
+=can be used to increment a numerical value (an integer or a float) by another numerical value;
+=can be used to augment a string with another string, a tuple with another tuple, or a list with any iterable type (string, tuple, list, set, dictionary, or even a file object (
.readlines()by default)). Each minimal unit of the second data structure will be taken out and added to the first data structure one by one. That’s why a string is broken into individual characters (since a character is a minimal unit of a string) before going into a list or another string;
Either way, you can always use
+multiple times in a single expression, like
1 + 2 + 3.14or
“Sam” + “Tom” + “Mary” + “Brenda”, but
+=can only be used once in one statement;
In any case, you’re not allowed to “add” a numerical value to an iterable type or vice versa in an operation; statements like
my_list = my_list + 3or
num1 += my_listwill result in a TypeError.
Besides addition and increment, let’s delve deeper into other operations.Group B:
/=always returns a float, even if no remainder is seen. That is,
5 /= 1returns
5 / 1returns
%=, just like
%, return integers;
All of these Group B operators only make mathematical sense, except
=make non-mathematical sense only when the right side is an integer. They work in the same fashion — both
data_structure = data_structure * 3and
data_structure *= 3replicate
data_structureand make a total of 3 copies in the end;
- For sets and dictionaries, all of the aforementioned operators (from Group A and Group B) would cease to work and cause errors.
Because you can’t add an integer to a list (iterable type), this will cause an error:
my_nums = [1, 2, 3, 4, 5] num = 6 my_nums += num print(my_nums)
You can convert the integer
#OUTPUT my_nums += num TypeError: 'int' object is not iterable
6into a string:
my_nums = [1, 2, 3, 4, 5] num = "6" my_nums += num print(my_nums)
# OUTPUT [1, 2, 3, 4, 5, '6']
But this might not be what you want, as
‘6’ is a string value when all the other members in the list are integers.
So you may want to convert it to a tuple or a list:
my_nums = [1, 2, 3, 4, 5] num = 6, my_nums += num print(my_nums)
Please take heed of the detail:
num = (6) is still an integer.
num = 6, or
num = (6,) makes it a tuple! The comma is the key! Not the parentheses!
# OUTPUT [1, 2, 3, 4, 5, 6]
Perfect! How about using
+ concatenation? Can you predict what will happen?
my_nums = [1, 2, 3, 4, 5] num = 6, my_nums = my_nums + num print(my_nums)
# OUTPUT my_nums = my_nums + num TypeError: can only concatenate list (not "tuple") to list
Haha! Why?! Reread my post carefully. :-)
+= don’t always do the same thing!