You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: materials/source/notes/session07.rst
+38Lines changed: 38 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -22,3 +22,41 @@ Zandra Eng
22
22
Issues that came up during the week.
23
23
====================================
24
24
25
+
Mutating vs. re-assigning
26
+
-------------------------
27
+
28
+
I've seen code like this in a few trigram solutions::
29
+
30
+
output = output + [follower]
31
+
32
+
(``output`` is a list of strings, follower is a single string)
33
+
34
+
What it does is add a new item to a list.
35
+
36
+
But is that an efficient way to do that?
37
+
38
+
If you are adding one element to a list -- append() is the way to go. This works fine, but it's creating a whole new list just to throw it away again:
39
+
40
+
output_list.append (random_trigram_followers)
41
+
42
+
and if you are adding another list of objects, you want to use extend(). The way it is now, you are actually doing:
43
+
44
+
1) create a list with random_trigram_followers in it.
45
+
2) create a new list with the contents of output_list the new list.
46
+
3) re-assign the name output_list to that new list.
47
+
4) throw away the original output_list and the temporary list you created for random_trigram_followers
48
+
49
+
That's a LOT of overhead!
50
+
51
+
Be cognizant of when you are mutating (changing) an object vs creating a new one and assigning it to the same name. When you do assignment (=) you are probably creating a new object.
52
+
53
+
54
+
+= is different -- it is the "in_place" operator, so:
55
+
56
+
a_list += another_list
57
+
58
+
does not create an new lists -- it adds to the original list "in place" -- it is identical to:
0 commit comments