1

I am trying to write a loop that replaces all the elements of the list with elements that are half a big. If the list is [1,2,3,4] the new list should read [0.5,1,1.5,2]. WITHOUT CREATING A NEW LIST!

I tried the following

for i in Glist:
    i = Glist[i]/2
    Glist.append(i)

And hot an error : list index out of range how to stop the loop?

also tried this:

for i in mylist:
    i = i/2
    mylist.append(i)

did not work

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Ron
  • 65
  • 1
  • 6
  • Does this answer your question? [Replace values in list using Python](https://stackoverflow.com/questions/1540049/replace-values-in-list-using-python) – mkrieger1 Feb 14 '20 at 17:45

2 Answers2

9

If you want to replace elements of a list, then the length of the list should not change, which append does. Instead:

for i,v in enumerate(Glist):
    Glist[i] = v/2.0
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
4

Note that iterating over a list while appending to it is a perfect recipe for an endless loop. Besides iiuc you want to modify the actual elements, here you're just appending to the end of the list.

You could use a regular for loop and just modify in-place with:

for i in range(len(Glist)):
    Glist[i] /= 2.

print(Glist)
[0.5, 1.0, 1.5, 2.0]
yatu
  • 86,083
  • 12
  • 84
  • 139