-4
List = ["I?", "Can", "!Not", "Do.", "It"]
l=[]
BadChars = ["?", "!", "."]
for i in List:
    for j in BadChars:
        if j in i:
            i=i.strip(j)
    l.append(i)
print(l)
print(List)

Output:

enter image description here

As you can see in the output the list was not overwritten even if the wrote i=i.strip(j). What is happening? Thanks in advance. I am newly learning python so this question may be dumb. This question raised in my mind when i was solving Change Character in Sublist in Stack Overflow. My question is "Why is List and l are having different values?"

  • Isn't the code doing what you want? `l` is now free of characters you want to exclude – Sheldore Mar 16 '19 at 01:00
  • Umm... You printed `l`, and it doesn't have the punctuation you didn't like that was in the `List` input. What did you expect to happen? Did you want `List` to change? – ShadowRanger Mar 16 '19 at 01:00
  • 1
    Similar question is posted [here](https://stackoverflow.com/questions/55192319/change-character-in-sublist) couple of minutes ago. It seems to be a homework – Sheldore Mar 16 '19 at 01:02
  • 1
    This question raised in my mind when i was solving Change Character in Sublist in Stack Overflow. My question is "Why is List and l are having different values?". This not a copied question or duplicate. Both are different. But lists used are same. – Challa Sai Bhanu Teja Mar 16 '19 at 01:06
  • 1
    When you loop over a list with `for i in List`, the variable `i` does not "remember" where it came from. Modifying its value does not transfer back to the list. – John Gordon Mar 16 '19 at 01:07

2 Answers2

2

To overwrite, use indexing:

List = ["I?", "Can", "!Not", "Do.", "It"]
l=[]
BadChars = ["?", "!", "."]
for i in range(len(List)):
    for j in BadChars:
        if j in List[i]:
            List[i] = List[i].strip(j)
    l.append(List[i])
print(l)
print(List)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

Your list was not “overwritten” because of two reasons, the first one is that strip returns a new string. The second one is that when you do i = i.strip(whatever) you are not overwriting the value pointed by i but pointing i to a new value. Therefore other references to the old value pointed by i are not affected because you didn’t change it at all.

ivissani
  • 2,614
  • 1
  • 18
  • 12