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]
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].
Related Questions
Do functions max( ), min( ), sum( ) work with all types of lists.
What is the difference between sort( ) and sorted( )?
Given two lists:
L1 = ["this", 'is', 'a', 'List'], L2 = ["this", ["is", "another"], "List"]
Which of the following expressions will cause an error and why?
- L1 == L2
- L1.upper( )
- L1[3].upper( )
- L2.upper( )
- L2[1].upper( )
- L2[1][1].upper( )
Given two lists:
L1 = ["this", 'is', 'a', 'List'], L2 = ["this", ["is", "another"], "List"]
Which of the following expressions will not result in error? Give output of expressions that do not result in error.
- L1 == L2
- L1.upper( )
- L1[3].upper( )
- L2.upper( )
- L2[1].upper( )
- L2[1][1].upper( )