On Oct 11, 9:19 pm, Jillian Calderon <[EMAIL PROTECTED]> wrote: > How do I define a 2d list? > > For instance, to define a 4 by 5 list, I wanted to do this: > n=4 > m=5 > world = [n][m] > However, it gives me an invalid syntax error saying the index is out > of range.
Here are some examples of how you can use list comprehensions to do this: In [1]: n=4 In [2]: m=5 In [3]: world = [[[] for ni in range(n)] for mi in range(m)] In [4]: world Out[4]: [[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]] In [5]: world[0][0] Out[5]: [] In [6]: len(world) Out[6]: 5 In [7]: len(world[0]) Out[7]: 4 In [8]: world = [[[ni+mi*n] for ni in range(n)] for mi in range(m)] In [9]: world Out[9]: [[[0], [1], [2], [3]], [[4], [5], [6], [7]], [[8], [9], [10], [11]], [[12], [13], [14], [15]], [[16], [17], [18], [19]]] Best, Tom -- http://mail.python.org/mailman/listinfo/python-list