Python Question / Quiz; What is the output of the following Python code, and why? Comment your answers below!

PythonPr's tweet image. Python Question / Quiz; What is the output of the following Python code, and why? Comment your answers below!

Answer: C. [8, 12] Solution: a and b are lists. Then there is a list comprehension that gives c. Let's analyze the list comprehension. Here is the trick to analyze list comps: 🗝️ Look for 3 things: `for`, `in`, and `if` (`if` is optional, sometimes it may not be there) +


I'm showing clear separations of for, in, and if here: [ (x) for (x) in (a) if (x not in b) ] We look at what is between `for` and `if`. It is: for x in a This is just like a regular for-loop: for x in a: That already looks so much simpler. Let's go on. +


Now we have to look at what comes at `if` and beyond, it is: if (x not in b) This is the familiar if-form. Simply think of it as nested within the `for` loop, like so: for x in a: if (x not in b): Even more simplified, familiar structure! Now only one part is remaining +


Why guess when you can know?


United States Trends
Loading...

Something went wrong.


Something went wrong.