Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate in python to For loop

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.

like image 877
GSSS MULTHAN Avatar asked Feb 28 '26 06:02

GSSS MULTHAN


1 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)
like image 76
Bob Avatar answered Mar 01 '26 19:03

Bob