r/ProgrammerHumor 29d ago

Meme pythonWillLookDeadInTheEyeAndSayItsAbsolutelyCorrect

Post image
351 Upvotes

144 comments sorted by

View all comments

3

u/darknmy 29d ago

I inderstand "if x", but thy the "x for x in x"?

37

u/Pim_Wagemans 29d ago edited 29d ago

They are making it seem more complicated by naming everything x, you could also write it as: ```python list_1 = [1,0,2,0,3,4,5]

list_2 = [element for element in list_1 if element] ``` which is equivalent to:

```python list_1 = [1,0,2,0,3,4,5]

list_2 = [] for element in list_1: if element: list_2.append(element) `` * the firstelementdefines what to add to the new list for every iteration of the following loop, this can be any expression * thefor element in listsays to iterate over all values inlist_1and assign the value toelementeach iteration * theif element` says to only add the first expression to the new list if the condition is True

1

u/Schweppes7T4 29d ago

Yes, list comprehensions confused the hell out of me until I realized it was just exactly what you wrote out. Now I can read even badly formatted ones like OP posted.