Computer Science
Change the above code so that it works as stated in previous question.
Python
Linear Lists
1 Like
Answer
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
SqLst = []
for num in NumLst:
SqLst.append(num * 2)
print(SqLst)
[4, 10, 2, 14, 6, 12, 16, 18]
Working
NumLst = [2, 5, 1, 7, 3, 6, 8, 9]
— This line creates a list calledNumLst
containing the given numbers [2, 5, 1, 7, 3, 6, 8, 9].SqLst = []
— This line initializes an empty list calledSqLst
.for num in NumLst:
— This line starts afor
loop that iterates over each elementnum
in theNumLst
list.SqLst.append(num * 2)
— Inside the loop, eachnum
is multiplied by 2, and the result is appended to theSqLst
list.print(SqLst)
— This line prints the resulting listSqLst
.
Answered By
2 Likes
Related Questions
How are lists internally stored ? How are 2D lists internally stored ?
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
Modify your previous code so that SqLst stores the doubled numbers in ascending order.
Consider a list ML = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write code using a list comprehension that takes the list ML and makes a new list that has only the even elements of this list in it.