Say I have a list of lists
>>> s = [ [1,2], [3,4], [5,6] ]
I can access the items of the second list:
>>> s[1][0]
3
>>> s[1][1]
4
And the whole second list as:
>>> s[1][:]
[3, 4]
But why does the following give me the second list as well?
>>> s[:][1]
[3, 4]
I thought it would give me the second item from each of the three lists.
One can use list comprehension to achieve this (as in question 13380993), but I'm curious how to properly understand s[:][1]
.
s[:][1]
means take a shallow copy ofs
and give me the first element from that... Whiles[1][:]
means give me a shallow copy ofs[1]
...You may be confusing somethings that you've seen that utilise
numpy
which allows extended slicing, eg:Which with normal lists, as you say, can be done with a list-comp:
s[:]
returns a copy of a list. The next[...]
applies to whatever the previous expression returned, and[1]
is still the second element of that list.If you wanted to have every second item, use a list comprehension:
Demo:
s[:]
makes a copy ofs
, so the following[1]
accesses the second element of that copy. Which is the same ass[1]
.s[1][:]
means a shallow copy of the second item ins
, which is[3,4]
.s[:][1]
means the second item in a shallow copy ofs
, which is also[3,4]
.Below is a demonstration:
Also,
[1]
returns the second item, not the first, because Python indexes start at0
.The behavior can be understood easily, if we decompose the command:
will return the entire list:
selecting [1] now gives the second list (python indexing starts at zero).