+ 1

list=[] list += "knock" list *=2 print(list)

As I'm new to python so I'm struggling to learn even small programs on python. it would be nice someone explain me this problem https://code.sololearn.com/c1LYW2C4cgvB/?ref=app

25th Oct 2020, 2:56 PM
Jaya Pratha
Jaya Pratha - avatar
2 Answers
+ 1
The '+' sign between a list and a string will split the string into characters and then append each character into the list. If you want to add the whole string into the list use the append() function, or insert the string between brackets like List += ["knock"] Or list.append("knock") The '*' operator, on a list, will repeat the reference of that list n times, like 2 times in this example. Try the following example to understand what i mean by reference: list = [["knock"]] list *= 2 list[1][0] = 'abc' print(list) output: [['abc'], ['abc']] this is because the '*' operator has multiplied not only the value but the whole object(resulting two objects having the same reference). so list[0][0] is the same object as list[1][0]. python works like a wizard.
25th Oct 2020, 3:09 PM
QTWizard
+ 1
Bl@<K H@t the question is about explaining what is going on in the program instead of telling changes from list*=2 to list*=1will overcome a problem that doesn't even exist
25th Oct 2020, 3:07 PM
Abhay
Abhay - avatar