3

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.

Thanks.

Community
  • 1
  • 1
O_O
  • 4,397
  • 18
  • 54
  • 69
  • @PaulHankin Personally IMHO i think, he didn't even know whether it was a generator for which he may not have caught the relation. So I don't think it's a complete duplicate. – Nagaraj Tantri Jun 05 '16 at 06:16
  • @NagarajTantri it seems reasonable to me to close it as a duplicate. The person asking the question can read the linked answer to understand the code they've found, and the question is so specific to that particular line of code that it doesn't add value to the site to exist as a separate question. – Paul Hankin Jun 05 '16 at 06:55
  • Can somebody explain why you don't need double parentheses when calling `set` with a generator expression? I'd assume the generator comprehension needs one pair, while `set` needs another. – Jan Christoph Terasa Jun 05 '16 at 06:58
  • @ChristophTerasa the set creator takes an iterator and with the parameter that are passed are stored and evaluated for a valid iterator if it can be created from that expression. And hence it works both ways: `set(o for o in x...)` and also `set((o for o in x..))` – Nagaraj Tantri Jun 05 '16 at 14:49

1 Answers1

5

That's equivalent to:

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

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.

Community
  • 1
  • 1
Nagaraj Tantri
  • 5,172
  • 12
  • 54
  • 78
  • 1
    Good answer. It is also worth noting that in this case the intermediate array `a` will be created in memory first, whereas a generator comprehension is lazily evaluated, saving memory (so they are *functionally* equivalent but not exactly the same). – Alex Bowe Jun 05 '16 at 06:12
  • @AlexBowe yes correct, good one. I was concentrating towards explaining him the kind of expression equivalent he can look for :) – Nagaraj Tantri Jun 05 '16 at 06:13