0

Code without List comprehension which is working fine

for i in range(1, int(b)+1):
    for j in list(combinations(a,i)):
        print("".join(j))

My attempt to list comprehension

[print("".join(j)) for j in list(combinations(a,i)) for i in range(1, int(b)+1)]

Error message: NameError: name 'i' is not defined

  • 3
    What is combinations? Is it a dictionary? – Riptide Sep 14 '20 at 07:33
  • 1
    There seem to be a lot of uncertainties in your code. What is b? What is a? As @Riptide aksed, what is combinations? The syntax of the list comprehension is incorrect. Please specify what result you want, and what you're not understanding. – Robo Mop Sep 14 '20 at 07:36
  • 1
    `print()` isn’t documented to return a value, you will get `None`. – DisappointedByUnaccountableMod Sep 14 '20 at 07:37
  • What is the obsession with one-liners? Your for-loop code doesn’t return a list so why does your attempt at a one-line version create a list? – DisappointedByUnaccountableMod Sep 14 '20 at 07:38
  • 3
    I, personally, highly discourage nested comprehensions, since they a real pain to read and understand – Tryph Sep 14 '20 at 07:38
  • @DavidZ provided a very nice answer (than he later deleted) explaining that the order of the `for` clauses need to be in the same order as you were doing in the `for` loops version: `[print("".join(j)) for i in range(1, int(b)+1) for j in list(combinations(a, i))]` – Adirio Sep 14 '20 at 08:02
  • 1
    @Adirio Thanks :-) I only deleted it because I thought the linked duplicate question covers the issue well enough, and I wanted to avoid splitting people's attention by having essentially the same thing posted both here and there. – David Z Sep 14 '20 at 08:22

0 Answers0