jensph
jensph

Reputation: 785

Python slicing of list of list

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].

Upvotes: 1

Views: 222

Answers (5)

user2555451
user2555451

Reputation:

s[1][:] means a shallow copy of the second item in s, which is [3,4].

s[:][1] means the second item in a shallow copy of s, which is also [3,4].

Below is a demonstration:

>>> s = [ [1,2], [3,4], [5,6] ]
>>> # Shallow copy of `s`
>>> s[:]
[[1, 2], [3, 4], [5, 6]]
>>> # Second item in that copy
>>> s[:][1]
[3, 4]
>>> # Second item in `s`
>>> s[1]
[3, 4]
>>> # Shallow copy of that item
>>> s[1][:]
[3, 4]
>>>

Also, [1] returns the second item, not the first, because Python indexes start at 0.

Upvotes: 2

fuesika
fuesika

Reputation: 3330

The behavior can be understood easily, if we decompose the command:

s[:]

will return the entire list:

[[1, 2], [3, 4], [5, 6]]

selecting [1] now gives the second list (python indexing starts at zero).

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121366

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:

[n[1] for n in s]

Demo:

>>> s = [ [1,2], [3,4], [5,6] ]
>>> [n[1] for n in s]
[2, 4, 6]

Upvotes: 5

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

s[:] makes a copy of s, so the following [1] accesses the second element of that copy. Which is the same as s[1].

>>> s = [ [1,2], [3,4], [5,6] ]
>>> s[1]
[3, 4]
>>> s[:][1]
[3, 4]

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142106

s[:][1] means take a shallow copy of s and give me the first element from that... While s[1][:] means give me a shallow copy of s[1]...

You may be confusing somethings that you've seen that utilise numpy which allows extended slicing, eg:

>>> a = np.array([ [1,2], [3,4], [5,6] ])
>>> a[:,1]
array([2, 4, 6])

Which with normal lists, as you say, can be done with a list-comp:

second_elements = [el[1] for el in s]

Upvotes: 2

Related Questions