Why x[i][:]=x[:][i] where x is a list of lists?

list, python

Solution

The behavior is pretty simple to understand if you break up the two indexing operations of each of your expressions into separate pieces.

- `x[1]` will be the second value from your list of lists (the list `[76, 80, 44, 30, 73]`).

- `x[1][:]` is a copy of `x[1]` (a slice that spans the whole list).

- `x[:]` is a (shallow) copy of `x` (the list of lists).

- `x[:][1]` is the second value from the copied list of lists, which is the same object as `x[1]`.

So, the two expressions work out to be equal. Note that because the first expression copies the list (with the `[:]` slice at the end), they're not both the same object (`x[1][:] is x[:][1]` will be `False`).

If you were using a 2D numpy array, you'd get different behavior, since you can slice in arbitrary dimensions (using slightly different syntax):

import numpy as np

x = np.array([[86, 92, 95, 78, 68],
              [76, 80, 44, 30, 73],
              [48, 85, 99, 35, 14],
              [3, 84, 50, 39, 47],
              [3, 7, 67, 28, 65],
              [19, 13, 98, 53, 33],
              [9, 97, 35, 25, 89],
              [48, 3, 48, 5, 1],
              [21, 40, 72, 61, 62],
              [58, 43, 84, 69, 26]])

print(x[1,:]) # prints the values of the second row: [76 80 44 30 73]
print(x[:,1]) # prints the values of the second column: [92 80 85 84  7 13 97  3 40 43]

This may be what you were looking for.

Problem

I am working on a list of lists and accessing columns has been very confusing. Let's assume x is defined as following: ``` x = [[int(np.random.rand()*100) for i in xrange(5)] for x in xrange(10)] pprint.pprint(x) ``` ``` [[86, 92, 95, 78, 68], [76, 80, 44, 30, 73], [48, 85, 99, 35, 14], [3, 84, 50, 39, 47], [3, 7, 67, 28, 65], [19, 13, 98, 53, 33], [9, 97, 35, 25, 89], [48, 3, 48, 5, 1], [21, 40, 72, 61, 62], [58, 43, 84, 69, 26]] ``` Now, both `x[1][:]` and `x[:][1]` yield the same result: ``` [76, 80, 44, 30, 73] ``` Can someone explain why? Thank you

Original source