1

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!

Vicky
  • 312
  • 2
  • 9
  • 19
  • Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – rdas Jun 13 '19 at 16:03
  • That question answers only how to remove items from a list, but my question is related to how to reset the list to its original value after every iteration?? – Vicky Jun 13 '19 at 16:07
  • You can make a copy of the existing list and use it whenever you like the original. Although there are different approaches, but this will do. – Hayat Jun 13 '19 at 16:13
  • you mean creating another variable for 'a'? Actually I'm trying to pop values and finding its sum one by one. While doing so I'm unable to retrieve its original value after the iteration.. – Vicky Jun 13 '19 at 16:19

1 Answers1

2

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))
Rage42
  • 91
  • 4
  • Thanks! Is there any possibility to achieve the same result,without using copy library/module? – Vicky Jun 13 '19 at 16:41