okcapp
okcapp

Reputation: 405

Python list comprehension: populating each inner-list with two variables

This works for creating the output [[0, 0], [1, 1], [2, 2], [0, 0], [1, 1], [2, 2], [0, 0], [1, 1], [2, 2]]:

[[k%3 for i in range(2)]for j in range(3)  for k in range(3)]

This works for creating the output [[0, 0], [0, 0], [0, 0], [1, 1], [1, 1], [1, 1], [2, 2], [2, 2], [2, 2]]:

[[j for i in range(2)]for j in range(3)  for k in range(3)]

Now, since my goal was to get output that looks like this: [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

I tried the following, but I got an error:

[[j,k%3 for i in range(2)]for j in range(3)  for k in range(3)]

The error is:

[[j,k%3 for i in range(2)]for j in range(3) for k in range(3)]

SyntaxError: invalid syntax

Upvotes: 2

Views: 63

Answers (2)

Jay
Jay

Reputation: 24905

You can create it as a tuple:

[[(j,k%3) for i in range(2)]for j in range(3)  for k in range(3)]

Output will be like below:

>>> [[(j,k%3) for i in range(2)]for j in range(3)  for k in range(3)]
[[(0, 0), (0, 0)], [(0, 1), (0, 1)], [(0, 2), (0, 2)], [(1, 0), (1, 0)], [(1, 1), (1, 1)], [(1, 2), (1, 2)], [(2, 0), (2, 0)], [(2, 1), (2, 1)], [(2, 2), (2, 2)]]

EDIT:

Expected Output Published by OP:

[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]

Code to achieve this:

  [[j,k] for j in range(3)  for k in range(3)]

Upvotes: 3

SpghttCd
SpghttCd

Reputation: 10890

if the expected result is

[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

imo you simply need

[[i, k] for i in range(3) for k in range(3)]

Upvotes: 2

Related Questions