Enumerate in python to For loop

Viewed 114

I want to convert enumerate to for loop.

subsets = [0]*15
subsets[0] = 2
subsets = [index + subsets[subsets[index]] for (index,value) in enumerate(subsets)]
print(subsets)

and the similar

subsets = [0]*15
subsets[0] = 2
for index,value in enumerate(subsets):
  subsets[index] = index + subsets[subsets[index]]
print(subsets)

But I am getting different results. Please help me about this.

3 Answers

In the first version you will compute everything based on the initial values of subsets, in the second version you will update the elements in place.

In particular, on the first iteration you will do subsets[0] = 0 + subsets[subsets[0]] = 0 + subsets[2] = 0. While for the first code subsets[0] will be 2 until the end of the execution.

An equivalent code would be

subsets = [0]*15
subsets[0] = 2
tmp = [0] * 15
for index,value in enumerate(subsets):
  tmp[index] = index + subsets[subsets[index]]
subsets = tmp
print(subsets)

In your first case the elements of the subsets list not change because you make a new list of subsets(Both names are same) and add the values in this list.

But In your second case you update your list values while iterating through it, THis is why you got different output.]

Execution of your second code.

subsets = [0]*15
subsets[0] = 2
for index,value in enumerate(subsets):
  subsets[index] = index + subsets[subsets[index]
print(subsets) ## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
  1. In the first iteration (index=0), index + subsets[subsets[index]] (subsets[index]=2) and after subsets[index]=2 (subsets[2]=0) result is now equal to 0 + 0 which is 0.
  2. In the second iteration (index=1), index + subsets[subsets[index]] (subsets[index]=0) and after subsets[0]=0 (because you change the zero'th value to 0 in first iteration) (subsets[2]=0) result is now equal to 1 + 0 which is 1.

similarly your sum of index + subsets[subsets[index]] is always equal to index value of the iteration.

I hope you understand

When you write subsets[index] = in the second example, the values of the original subsets get overwritten and is used in the next iteration, etc.

This is how to write the loop, if you don't want enumerate, use for index in range(len(subsets)) and subsets[subsets[index]] instead of subsets[value].

output = [] 
subsets = [2] + [0]*14
for index, value in enumerate(subsets): 
    output.append(index + subsets[value])
print(output)
Related