O_O O_O - 7 months ago 21
Python Question

For loops in Python

Can someone explain to me this line

set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])

from Calculate difference in keys contained in two Python dictionaries

I'm new to Python and have never seen any programming language written similar to "o for o" and am unable to find any reference to understand what this means.



That's equivalent to:

a = []
for o in self.intersect:
    if self.pass_dict[o] != self.current_dict[0]:

new_value = set(a)

With generators: the o for o in self.intersect ... means, loop through each element and apply the condition inside the for loop i.e. if self.pass_dict[o] != self.current_dict[0] and return each element to a set.

The point is, you should learn what are List Comprehension and Generators in python and also browse links like Generator expressions vs list comprehension

As @Alex updated, which would give you an update: The variable a is basically created in memory and returned to the set function.