About using this (+) in List . censor


#1




I used a different way to append items in list..

I'm supposed to write on line 6, 8:
new.append("*" * len(i))
new.append.(i)

but i write
new += ["*" * len(i)]
new += [i]

and it works!but I'm not really sure if it's right one and if I can keep using this(i dont think I would use again next time though,,) .
can anyone explain about this arithmetic operation(+) in list?
is it ok to use in list??


def censor(text, word):
    text_list = text.split(" ") #text = "ddd ggg"  #text_list = [ddd, ggg]
    new = []
    for i in text_list:
        if i == word:
            new += ["*" * len(i)]
        else:
            new += [i] #n+="ddd"-->n=['d','d','d']----n+=["ddd"]-->n=["ddd"]
    return " ".join(new)

print censor("oh yeah", "oh")


#2

+ and += are different operators, for mutable values += does not use +, it's instead in-place add, as opposed to creating a new list that is the concatenation of both and replacing the original.

+= for list behaves the same as list.extend

a = []
b = [1, 2]

# the following three are equivalent:

a.extend(b)

a += b

for elem in b:
    a.append(elem)

#3

it's instead in-place add, as opposed to creating a new list that is the concatenation of both and replacing the original. <-I cannot understand this words ㅠㅠㅠ
can you explain with some example.....


#4

a = []
b = [1, 2]

a += b

# is not the same as

a = a + b

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.