Search code examples
pythonpython-2.7loopsiteration

For loop iterating not executed with condition set inside


I have a simple python loop that iterate over a 2D list which has 1000 sublist inside. Each sublist will contain 3 string values. I only want to change the sublists which are after the 365th sublist. I also have a very trivial condition which will decide if an operation will be applied to the element. My minimum code is as follows:

def change_list(arr):
    for i in range(len(arr)):
        if i < 365:
            pass
        else:
            arr[i][1] = str(int(arr[i][1]) * 2)

When apply this function in main I'll simply invoke this function as: change_list(parsed_lines). For parsed lines, I'll just give a simple example:

parsed_lines = [["afkj","12","234"]] * 1000

My function will do the "multiply by 2" operation on all sublists, which is an unexpected behavior. I've tried not using conditions, but results in the same behavior.

for i in range(365, len(arr)):
    arr[i][1] = str(int(arr[i][1]) * 2)

Then I tried the other way to iterate my arr as:

for line in arr:
    if arr.index(line) < 365:
        print("I'm less than 365")
    else:
        line[1] = str(int(line[1]) * 2)

but this iteration will never execute the block under else. I am very confused by this, hope someone can help.

Update:

The expected behavior should be:

  1. For arr[0: 365], the sublist will stay the same as: [["afkj","12","234"]]
  2. For arr[365:], the sublist will be: [["afkj","24","234"]]

Solution

  • Your problem, as described, is not in the program, but in the test set. parsed_lines = [["afkj","12","234"]] * 1000 creates a list of 1000 references to the same list ["afkj","12","234"]. When it is modified through any of those references (say, above 365), it is seen as modified through any of those references (even below 365). In other words, parsed_lines[0][0]='foo' makes all fisrt elements in all sublists 'foo'.