0

I am confused about where the r in the below code comes from in the combinations function. A bit new to Python.

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
sj95126
  • 6,520
  • 2
  • 15
  • 34
Furqan_25
  • 29
  • 6
  • From `for r in range(len(s)+1)`. – adamkwm Jul 17 '22 at 03:02
  • 2
    [https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries) – wwii Jul 17 '22 at 03:10

1 Answers1

5

The variable r is the iterable of the generator comprehension statement passed to the function chain.from_iterable(). If you unpack the comprehension, it would be analogous to the below code.

from itertools import chain, combinations

def powerset(iterable):
    s = list(iterable)
    res = []
    for r in range(len(s) + 1):
        res.append(combinations(s, r))
    return chain.from_iterable(res)

Both the above for loop and the provided generator comprehension use the variable r as the iterator.

You can read more about generator comprehension from this Stack Overflow answer. While not identical, you can read more about list comprehension in the Python Documentation here.

Jacob Lee
  • 4,405
  • 2
  • 16
  • 37