Computer Science
Create a list SqLst that stores the doubles of elements of another list NumLst. Following code is trying to achieve this. Will this code work as desired ? What will be stored in SqLst after following code ?
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
SqLst = NumLst * 2
Answer
No, the above code will not work as desired.
[2, 5, 1, 7, 3, 6, 8, 9, 2, 5, 1, 7, 3, 6, 8, 9] will be stored in SqLst after the above code is executed. The multiplication operator * with a list NumLst
, duplicates the elements of the list NumLst
by 2 times.
Explanation
The correct code is:
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
SqLst = []
for num in NumLst:
SqLst.append(num * 2)
print(SqLst)
Output
[4, 10, 2, 14, 6, 12, 16, 18]