Computer Science

What is the difference between following two expressions, if lst is given as [1, 3, 5]

(i) lst * 3 and lst *= 3
(ii) lst + 3 and lst += [3]

Python List Manipulation

48 Likes

Answer

(i)

lst * 3 will give [1, 3, 5, 1, 3, 5, 1, 3, 5] but the original lst will remains unchanged, it will be [1, 3, 5] only.
lst *= 3 will also give [1, 3, 5, 1, 3, 5, 1, 3, 5] only but it will assign this result back to lst so lst will be changed to [1, 3, 5, 1, 3, 5, 1, 3, 5].

(ii)

lst + 3 will cause an error as both operands of + operator should be of same type but here one operand is list and the other integer.
lst += [3] will add 3 to the end of lst so lst becomes [1, 3, 5, 3].

Answered By

22 Likes


Related Questions