0

I'm supposed to find the largest number in a list, and then change all the elements of the list to that number. But when I print the output after the iteration, it still hasn't changed. What am I doing wrong please ?

Ar =[5,4,11]
ArMax = max(Ar)

for i in Ar:
   i = ArMax

print(Ar)
Prune
  • 76,765
  • 14
  • 60
  • 81
Metal.days
  • 85
  • 7
  • @jpp I nominated this for reopening, since the duplicate you listed doesn't deal with the assignment error. – Prune Oct 02 '18 at 16:16
  • 1
    @Prune, Above is now a *precise* dup. Always worth checking if there are other valid dups around. I'm sure I can find half a dozen of these! – jpp Oct 02 '18 at 16:21
  • Good work! I missed that on my check -- and not finding a dup was a surprise. Since you apparently used your hammer already, I brought mine -- but you get credit for the find. – Prune Oct 02 '18 at 16:23

2 Answers2

2

The list doesn't change because you've done nothing to change the list. Your list is Ar -- where have you assigned a new value to anything in that list? Nowhere. All you did was to create a local variable to take on the values in Ar, and then change the value of that variable. You never touched the original list. Instead, you have to change the list elements themselves, not their copies. Keeping close to your present code:

for i in range(len(Ar)):
    Ar[i] = ArMax

Another way would be to create a new list with those items in it, and simply replace the original list all at once:

Ar = [ArMax] * len(Ar)

This looks to see how long the current list is with len(Ar). Then it takes a one-element list with the max value and replicates it that many times. That new list becomes the new value of Ar.

Prune
  • 76,765
  • 14
  • 60
  • 81
0

i = ArMax does not actually assign values to the list because the values of i are copies of the elements in the list. If you want to fix this, try:

for i in xrange(len(Ar)):
    Ar[i] = ArMax
kcborys
  • 316
  • 1
  • 11