Plokavian Nerve Gas Plokavian Nerve Gas - 1 year ago 65
Python Question

Why does pythons slice indexing give counter intuitive results?

If I have a 2D list in python

and I want to create a slice of that 2D list, where I select all the elements from the first index and a single on from the second.


Data = [[a,b,c],[d,e,f],[h,i,g]]

and I want the list;

raw_data = [b,e,i]

Why does doing something like;

raw_data = Data[:][1]

not give the desired output?
I have specified the whole first index and the 1 index for the second.
Instead I get the output that is;

raw_data = [d,e,f]

Which is what I would expect to get from;

raw_data = Data[1][:]

raw_data = [d,e,f]


Data[1][:] = Data[:][1]

Which is not compatible with my mental model of how lists work in python.

Instead I have to use a loop to do it;

raw_data = []

for i in xrange(0,len(Data),1):

So my question is, can anyone explain why
Data[1][:] = Data[:][1]

Thanks for reading!

Answer Source

lst[:] has no explicit start an no explicit end, so according to the Python documentation, it will return a copy of the list starting at the start and ending at the end of the list. In other words, it will return a copy of same list you have before. So:

>>> Data = [['a','b','c'],['d','e','f'],['h','i','g']]
>>> Data[:]
[['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'g']]

So when you say Data[:], that will evaluate to the same as a copy of Data, meaning that Data[:][1] essentially is just Data[1], which is [d,e,f]

If you do it the other way:

>>> Data[1]
['d', 'e', 'f']
>>> Data[1][:]
['d', 'e', 'f']

You get the second element in data, [d,e,f], then you use that same list slicing syntax as before to get that same list again.

To get what you want, I'd use a list comprehension:

>>> [x[1] for x in Data]
['b', 'e', 'i']

Simple as that.