1

I am translating some code from Python to C++. I came across the following:

set(x for listX in listY for x in listX)

I am quite well-versed in C++ and know some basic constructs in Python. In the above code, I know that a set is being created but I do not understand the code inside the brackets. Any help?

Rohan
  • 50,238
  • 11
  • 84
  • 85
Mika
  • 1,125
  • 5
  • 20
  • 34

2 Answers2

6

listY is probably something like the structure below, so the expanded code is:

listY = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = set()
for listX in listY:
    for x in listX:
        result.add(x)

notice: sets won't allow duplicate entries

andrean
  • 6,467
  • 2
  • 32
  • 43
  • 1
    The generator expression has been passed to `set`, so everything is evaluated immediately - inside the `set` implementation, sure. – Karl Knechtel Sep 01 '12 at 07:24
3

It is a generator comprehension, analogous to a list comprehension. See this previous question for some info comparing them.

Community
  • 1
  • 1
BrenBarn
  • 228,001
  • 34
  • 392
  • 371
  • Thanks for the link, I found a similar example in [generator comprehension](http://www.python.org/dev/peps/pep-0289/) – Mika Sep 01 '12 at 06:57