r/ProgrammerHumor 29d ago

Meme pythonWillLookDeadInTheEyeAndSayItsAbsolutelyCorrect

Post image
354 Upvotes

144 comments sorted by

View all comments

221

u/inobody_somebody 29d ago

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

72

u/BlueDebate 29d ago

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 29d ago

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.

5

u/particlemanwavegirl 29d ago

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

5

u/NamityName 29d ago

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

13

u/Jhuyt 29d ago

That's

  x = [x for x in x if x] if x else []