Nested list comprehension examples

Welcome to Python Land Forums The Python Tutorial Nested list comprehension examples

Viewing 1 reply thread
  • Author
    • #1665

      Hello, Thanks for your work on this site! I feel like it’s coming along well.

      I was working through the Language Deep Dives, List Comprehension page, when under More Advanced Examples, I was running into errors in my REPL. I’m wondering if I am doing something wrong or if there is an error in the examples.

      I’m assuming that there is no carryover from previous examples.

      I entered the first line:
      >>> [[j for j in range(3)] for i in range(4)]
      And I got back the output shown.

      After entering the second line:
      >>> [value for sublist in [m for value in sublist]]
      I get an error:

      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      NameError: name 'sublist' is not defined

      And the third line:

      >>> [value
           for sublist in m
           for value in sublist]

      I get an error:

      Traceback (most recent call last):
        File "<stdin>", line 2, in <module>
      NameError: name 'm' is not defined

      After playing around with it, I believe what happened is that the first line should be assigning that list comprehension to m, and the second line is not supposed to have the second set of brackets around m for value in sublist. After assigning the first line to m, the third line flattens the matrix as shown.

      Is that correct or am I doing something wrong?

    • #1670
      Erik van Baaren

      Thank you for letting me know.

      There were two errors in the examples. First of all, the result of the first example should be assigned to a variable m. That variable is used in the next two examples.

      Second: there were too many block quotes in the first ‘flatten’ example. I fixed both errors, so please try again!

Viewing 1 reply thread
  • You must be logged in to reply to this topic.