-1

Hi can someone please explain to me why this function isn't working as I intended it to? I know I can do it by using the index of the list to check if the element is equal to a variable but why can't this method work?

Expectations- I wanted this function to change the element in list (stored) if it matches a particular value. IE chance letter c to the # symbol in this example.

Results - The list (stored) that is printed will have no difference and end up print [a,b,c,d,e]

Code

stored = ["a", "b", "c", "d", "e"]
def if_match():
  for letters in stored:
    if letters == "c":
      letters = "#"
  print stored
Yeo Bryan
  • 331
  • 4
  • 24

1 Answers1

0

It doesn't work because letters is a variable used just to iterate over the list. To actually change the value you need to do:

for x in range(len(stored)):
    if stored[x] == "c":
        stored[x] = "#"

Or you can enumerate through the list like this:

for index, value in enumerate(stored):
    if value == "c":
        stored[index] = "#"

This will actually change the value of "c" to "#".

  • Doesnt letters refer to each variable in the list ? So when that particular variable is equal to what i am checking it against i change the value of the variable? – Yeo Bryan Apr 23 '18 at 02:39
  • @YeoBryan it changes the value of the variable, but not the value present in the list –  Apr 23 '18 at 02:42
  • @YeoBryan please accept my answer if it helped you –  Apr 23 '18 at 02:49
  • It is not a copy. – juanpa.arrivillaga Apr 23 '18 at 02:50
  • @juanpa.arrivillaga can you please provide clarification as to why –  Apr 23 '18 at 02:50
  • Because it is not a copy. Put some mutable object in a list, iterate over the list, mutate the object, and you will see it is not a copy – juanpa.arrivillaga Apr 23 '18 at 02:54
  • The keys point: assignment never mutates – juanpa.arrivillaga Apr 23 '18 at 02:55
  • @juanpa.arrivillaga so why doesn't changing the value of the variable letters change the value inside the list –  Apr 23 '18 at 02:55
  • Because *assignment never mutates* – juanpa.arrivillaga Apr 23 '18 at 02:58
  • stored = [ "a","b","c","d","e"]     n=0     for i in range(5):       if stored[n] == "c":         stored[n] = "#"         n+=1       else:         n+=1     print stored But for this code it works? Sorry but i am not rly sure why thats the case – Yeo Bryan Apr 23 '18 at 03:03
  • @YeoBryan Use proper formatting for your comment. I don't realy understand what you mean. Also, if this works, make sure you accept it –  Apr 23 '18 at 03:11