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
In the Code Style chapter examples - Short Ways to Manipulate Lists there is an example "Add three to all list members."
"bad"
foriinrange(len(a)):
a[i] +=3
"good"
a= [i+3foriina]
Unfortunately the "bad" and "good" examples do a different things:
"bad" modifies the original list in place
"good" creates a new modified list and does not change the original object - not exactly "Add three to all list members."
Although the "good" code looks cleaner the result could be unwanted for example in case of huge lists or required side-effect of modifying the original list. The code at least needs an explanation.
The text was updated successfully, but these errors were encountered:
Excuse my delayed reply. I am still learning Python a lot and in many cases I do not know what is the best way to perform certain task in the language. Also I am not sure if I know English good enough to contribute to an English book. So certainly I need a discussion first :)
Regarding the example above I would explain:
For large lists it could be inappropriate to create a new list to replace the old one because of memory requirements. In such cases the good solution is to modify the list in-place:
fori, _inenumerate(a):
a[i] +=3
PS: Originally I thought that the code below would be the right solution but as the original "good" solution it also creates a new list and only then it assigns its elements to the original list.
In the Code Style chapter examples - Short Ways to Manipulate Lists there is an example "Add three to all list members."
"bad"
"good"
Unfortunately the "bad" and "good" examples do a different things:
Although the "good" code looks cleaner the result could be unwanted for example in case of huge lists or required side-effect of modifying the original list. The code at least needs an explanation.
The text was updated successfully, but these errors were encountered: