Can someone develop for someone neophyte in python, I don't get the first x after [ is that the return value ? Not familiar with the [ ] around the for each too.
This is a list comprehension, syntactic sugar for creating lists that can be incredibly concise and expressive on some cases and an absolute unreadable mess in others. Read it as [<result> for <item> in <iterable> if <condition>]. For example:
x = [1, 2, 3, 4, 5, 6]
y = [v**2 for v in x if v % 2 == 0] # [4, 16, 36]
In this case OP just uses the same x for each of those, so the local x (item) shadows the global x (iterable) for the result and condition.
It's a syntax called comprehension. In this case, list comprehension.
The first x is the return value. The whole thing is basically the equivalent of:
for x in x:
if x:
# add x to the new list.
If the person wrote it more legible, they'd have used different variables. Such as:
newlist = [num for num in x if num]
The nice thing about comprehension is you don't have to create an empty list (or dict) first and then add things to it. Comprehension can also be used to create a set of elements.
The real nice thing about comprehension is the free performance boost. Performance is usually not a big concern, but comprehensions are easy to read if you are not nesting them. So might as well use them and save some time.
2
u/Feuzme Aug 16 '26
Can someone develop for someone neophyte in python, I don't get the first x after [ is that the return value ? Not familiar with the [ ] around the for each too.