2

I know that to generate a list in Python you can use something like:

l = [i**2 for i in range(5)]

instead of using for loop like:

l = []
for i in range(5):
    l.append(i**5)

Is there a way to do 2D lists without using for loops like this:

map = [[]]

for x in range(10):
    row = []
    for y in range(10):
        row.append((x+y)**2)
    map.append(row)

Is there any other alternatives to represent 2D arrays in Python ?

3 Answers 3

9

Use a list comprehension here too:

>>> [ [(x+y)**2 for y in range(10)] for x in range(10)]
[[0, 1, 4, 9, 16, 25, 36, 49, 64, 81], [1, 4, 9, 16, 25, 36, 49, 64, 81, 100], [4, 9, 16, 25, 36, 49, 64, 81, 100, 121], [9, 16, 25, 36, 49, 64, 81, 100, 121, 144], [16, 25, 36, 49, 64, 81, 100, 121, 144, 169], [25, 36, 49, 64, 81, 100, 121, 144, 169, 196], [36, 49, 64, 81, 100, 121, 144, 169, 196, 225], [49, 64, 81, 100, 121, 144, 169, 196, 225, 256], [64, 81, 100, 121, 144, 169, 196, 225, 256, 289], [81, 100, 121, 144, 169, 196, 225, 256, 289, 324]]
Sign up to request clarification or add additional context in comments.

Comments

2

The more efficient way to do that is using numpy.meshgrid(). Here you have an example:

i = np.arange(1,10)
I,J = np.meshgrid(i,i)
array = (I+J)**2

and array has the desired form.

You could compare the performance between your method and meshgrid. Meshgrid is C-implemented, so it's very fast!

If you need a list from an array, you could use the array.tolist() method.

Comments

0

You might also consider implementing n-d arrays using numpy, a scientific computing package for Python. Numpy array objects confer a few advantages over nested lists:

  • n-d array slicing, for example (taken from numpy documentation):

    x = np.array([[1, 2, 3], [4, 5, 6]], np.int32) #creates the array
    x[:,1] # returns the first column
    
  • easy manipulation of n-d arrays with methods such as transpose, reshape and resize.

  • easy implementation of mathematical operations on arrays.

Of course this may be more machinery than you actually need, so it could be the case that nested list comprehension is sufficient for your purposes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.