reset password
Author Message
rabbott
Posts: 1649
Posted 11:33 Sep 24, 2018 |

I wasn't sure about what the nested comprehension we talked about would produce, so when I got back to my office I tried it. (One of the nice things about Python is how easy it is to try things.) I used Colabratory's Jupyter. For each  x value you get a separate sublist.

result = [[(x, y) for y in range(3)] for x in range(4)]
print(result)

=> [[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], [(3, 0), (3, 1), (3, 2)]]

To see why this makes sense consider this comprehension.

result = [[x] for x in range(4)]
print(result)

=> [[0], [1], [2], [3]]

For each x one gets a separate list [x]. The comprehension embedded in those lists generate y values for each list.

Last edited by rabbott at 11:50 Sep 24, 2018.