dlpnewbie96 dlpnewbie96 - 1 year ago 67
Python Question

How to avoid side effect in for loop using slicing operator in a list in python?

This is quoted from the link : http://www.python-course.eu/for_loop.php -
To avoid these side effects, it's best to work on a copy by using the slicing operator, as can be seen in the next example:

colours = ["red"]
for i in colours[:]:
if i == "red":
colours += ["black"]
if i == "black":
colours += ["white"]
print colours


The output is :

['red', 'black']


My question is: does the statement
colours[:]
makes a copy of the colours list and the for loop works on the copy instead of the original list? If it is so, then how the
["balck"]
is appended to the original colour list?

Answer Source

does the statement colours[:] makes a copy of the colours list: Yes.

and the for loop works on the copy instead of the original list? Yes, but be careful what you mean by "works on". The variable i takes its values from a copy of list colours. However, the references to colours such as in the line colours += ["black"] refer to the original list. That is just what the code wants, so it works.

If it is so, then how the ["balck"] is appended to the original colour list? This is because the line that does the appending refers to the original list and not the copy of the list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download