+ 3
Explanation for the code(Python)
I've come across this code in Sololearn " challenge" but failed to grasp the essence of it. Can someone help me with it? y=[x if x==1 else x*2 for x in ["1","2"]][0] print (y) The output is "11",but how?
5 Respostas
+ 5
In short, "1"*2 = "11". It is Python string multiplication.
Note that x==1 is false both times.
"1"==1 (false)
"2"==1 (false)
So it uses x*2 on both elements.
After list comprehension is done, it makes
["11", "22"]
And y= ["11", "22"][0] = "11"
print(y)
Output:
"11"
+ 4
Brian Thanks very much!!!
+ 3
Now we know Lothar is a human like us 😄!
+ 2
Lothar the presumption of a typo is unnecessary. It works as it was originally presented. Try removing the [0] from the end. Then y is assigned the intermediate list ["11", "22"], and then that is what gets printed.