-1

Suppose I have a list nums = [1,3,2,5,6] and I want to subtract each element's value by 1. Now I wrote codes like

for i in nums:
    i -= 1

However, when I print nums its values did not change. I'm wondering why it doesn't work, and whether there is an elegant way in Python to do this. Thank you!

Austin
  • 33
  • 3

2 Answers2

1

i is a local variable and does not reflect the actual objects in nums, only their values. The best way to do this is to use a list comprehension:

nums = [i - 1 for i in nums]

If you need to retain references to nums:

nums[:] = = [i - 1 for i in nums]

Demo:

>>> nums = [1, 2, 3]
>>> [i - 1 for i in nums]
[0, 1, 2]
iz_
  • 15,923
  • 3
  • 25
  • 40
0

The for loop sets i to successive values in the list, not references into the list. There are a couple ways to accomplish what you want:

nums = [i-1 for i in nums]

Is one way. If you need to keep the same list object you could do:

for ndx in xrange(len(nums)):
    nums[ndx] -= 1
B. Morris
  • 630
  • 3
  • 15
  • `range` if using Python 3. – iz_ Dec 02 '18 at 04:16
  • Visualize this with http://www.pythontutor.com/visualize.html#code=nums%20%3D%20list%28range%285%29%29%0Afor%20i%20in%20nums%3A%0A%20%20%20%20i%20-%3D%201&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false – Ben Dec 02 '18 at 04:17