Vicky
Vicky

Reputation: 322

Python: How to reset the list to original value inside the for loop for every iteration?

I'm trying to pop every values one by one from a list in order to find the min and max sum. While doing that I'm resetting the list to its original value after every iteration, but it doesn't seems to be working...

a=[1,2,3,4,5]
res=[]
for i in range(len(a)):
    #print(a)
    lst=a
    #print(lst)
    lst.pop(i)
    print(lst)
    res.append(sum(lst))
print(min(res))
print(max(res))

[2, 3, 4, 5]
[2, 4, 5]
[2, 4]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-33-42daa1037d37> in <module>
      5     lst=a
      6     #print(lst)
----> 7     lst.pop(i)
      8     print(lst)
      9     res.append(sum(lst))

IndexError: pop index out of range

I'm resetting the "lst" to "a" after every iteration, but its not working as expected.

Expected result:

[2, 3, 4, 5]
[1, 3, 4, 5]
[1, 2, 4, 5]
[1, 2, 3, 5]
[1, 2, 3, 4]
10
14

Any help would be appreciated!

Upvotes: 1

Views: 4321

Answers (1)

Rage42
Rage42

Reputation: 101

The operator "=" doesn't duplicate your list into two different object. In fact "lst" and "a" both refer to the same object.

Which means if you modify "lst" you will also modify "a" :

>>> a=[1,2,3,4,5]
>>> lst = a
>>> lst.pop(0)
>>> print(a)
[2, 3, 4, 5]

You can change this behavior using the module copy and its function deepcopy. It will duplicate your list and not affect your original one.

import copy

a=[1,2,3,4,5]
res=[]
for i in range(len(a)):
    #print(a)
    lst= copy.deepcopy(a)
    #print(lst)
    lst.pop(i)
    print(lst)
    res.append(sum(lst))
print(min(res))
print(max(res))

Upvotes: 2

Related Questions