-2

This should store [1,2,3,4,5] in the list but it stores [1,1,1,1,1] instead:

l=[0]*5
for x in range(5):
    y=1
    l[x] = y
    y+=1
print (l)
Sumit
  • 486
  • 4
  • 16
  • 1
    you are initializing `y=1` inside for loop for every run. Take it outside loop. – Anil_M Sep 20 '17 at 14:33
  • I am not sure this question was closed with the correct duplicate in mind; the error had not much to do with the immutability of ints; it is a typical new programmer question, and if SO can't answer, where can they turn to for help with this sort of mistakes? – Reblochon Masque Sep 20 '17 at 14:42
  • the duplicate closure was a mistake. But there isn't much to answer there. For me it looks very much like a typo... Anil_M solved this in comments... – Jean-François Fabre Sep 20 '17 at 21:47
  • 1
    Note that it's much more pythonic to do `l = list(range(1, 6))` – Justin Sep 20 '17 at 21:49

1 Answers1

4

you must place y = 1 before entering the for loop:

my_list = [0] * 5
y = 1
for x in range(5):
    my_list[x] = y
    y += 1
print(my_list)

I changed the name of your list to my_list; using l is a source of confusion with 1...

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80