What Is the Output of This python Code?
Question :
x = [10, 20, 30]
print(x * 2)
Options :
A) [10, 20, 30, 10, 20, 30]
B) [20, 40, 60]
C) [10, 20, 30, 2]
D) Error
correct answer :
A) [10, 20, 30, 10, 20, 30]
Explanation :
First we create a list :
x = [10, 20, 30]
The list contains 3 elements.
Step 1 - List Multiplication :
x * 2
In python multiplying a list does not multiply the values.
Instead it repeats the list elements.
Step 2 - Repeating the list :
[10, 20, 30] * 2
Python repeats the list 2 times.
SO the result becomes:
[10, 20, 30, 10, 20, 30]
Step 3 - Print statement :
print(x * 2)
The output wiil be :
[10, 20, 30, 10, 20, 30]
Final Output :
[10, 20, 30, 10, 20, 30]
Key points :
The * operator with list repeats the list elements not the values.
Example :
[1, 2] * 3
Output:
[1, 2, 1, 2, 1, 2]
Practice daily Python coding challenges to improve your programming and logical thinking skills.
Happy coding ❤️

No comments:
Post a Comment