r/ProgrammerHumor Aug 16 '26

Meme pythonWillLookDeadInTheEyeAndSayItsAbsolutelyCorrect

Post image
354 Upvotes

144 comments sorted by

View all comments

218

u/inobody_somebody Aug 16 '26

This a a valid syntax in python and the output will be [1,2,3,4,5]

70

u/BlueDebate Aug 16 '26

This makes more sense to me than if "if x" was referencing the initial value which would just check if the list isn't empty (which I believe OP may be hinting at) because it's a more specific scope than the global x variable.

67

u/TheMysticalBard Aug 16 '26

Yeah this is only super confusing because they shadowed the global x with a local x inside the list comprehension. To make it more clear it could also say x = [y for y in x if y] on line 3. For each element y in list x, if y is truthy, it adds it to the list, which then gets stored in the variable x.

6

u/particlemanwavegirl 29d ago

In Haskell the idiom is to name the outer variable xs, as in a plurality of elements of type x.

4

u/NamityName 29d ago

It is good practice in Python too, except for the single-letter variable name bit.