Explanation for the code(Python) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

7th Jun 2022, 8:02 AM
Avitus
Avitus - avatar
5 Answers
+ 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"
7th Jun 2022, 8:14 AM
Brian
Brian - avatar
+ 5
Brian , Avitus , sorry, you are right. oops - i must have been blind!
7th Jun 2022, 1:21 PM
Lothar
Lothar - avatar
+ 4
Brian Thanks very much!!!
7th Jun 2022, 8:17 AM
Avitus
Avitus - avatar
+ 3
Now we know Lothar is a human like us 😄!
7th Jun 2022, 1:38 PM
Brian
Brian - avatar
+ 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.
7th Jun 2022, 12:39 PM
Brian
Brian - avatar