0

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
  • 506,650
  • 124
  • 909
  • 1,183
Ron
  • 55
  • 1
  • 5
  • 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

8

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
  • 46,905
  • 10
  • 55
  • 92
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
  • 80,714
  • 11
  • 64
  • 111