-1

I have a given list, with 49 variables each with a value between 1-5. I want to change the value of all variable which is equal to 5 to zero. Here is what I’ve tried:

 For element in listb:
        If element == 5:
            element = 0

But it doesn’t have any affect, what is the problem? Thanks Vendel

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

1 Answers1

0

Using list comprehension:

listb = [n if n!=5 else 0 for n in listb]

Which is a more efficient alternative to

 for index in range(listb):
    if listb[index] == 5:
        listb[index]  = 0

Infact in for element in listb: element is a copied primitive.

This would be different if we had:

listb = [[1],[5],[3]]
for element in listb: #element is a copied reference, but to the same element in listb
    if element[0] == 5:
        element[0] = 0
Attersson
  • 4,755
  • 1
  • 15
  • 29
  • What's a "copied element"? ``element`` will be a reference to the actual item, so if it's mutable and you change it in place, it will also change within ``listb``. – Mike Scotty Jun 13 '18 at 14:33
  • @MikeScotty copied from python shell: `>>> listb = [1,2,3,4,5,1,2,3,4,5] >>> [n if n!=5 else 0 for n in listb] [1, 2, 3, 4, 0, 1, 2, 3, 4, 0] >>> for element in listb: ... element = 5 ... >>> listb [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] >>>` – Attersson Jun 13 '18 at 14:46
  • That's why I wrote ``if it's mutable``. Example: ``listb = [ [] ] for item in listb: item.append(1) print(listb) `` Result: ``[[1]]`` – Mike Scotty Jun 13 '18 at 14:51
  • Exactly. In that case python will internally copy a reference to the same list (the inner []) and that is mutable. But being a primitive, element, in the main example, is just copied. We probably mean the same thing – Attersson Jun 13 '18 at 14:54