Search code examples
pythonlistindexingslicesublist

Create list out of a particular element of sublists


My title is probably incredibly confusing, so I'll just give an example. For the following list:

 x = [ [1,2,3], [4,5,6], [7,8,9] ]

So, if you wanted from an index of one, the resultant list would be:

 [2,5,8]

Is there a short way to do this? Obviously you can iterate through the outside list and simply grab each element of index 1, but is there any easy way to do this in one line with, for example, slce notation?

I'm aware that it's possible to do this in one line with something like:

 list(map(lambda f : f[1], x))

But that's exactly what I described above (just using an implicit loop).

If it helps, it is safe to assume that all the elements will be indexable.


Solution

  • No matter what you do, there will always be implicit looping somewhere.

    You can also use zip (look ma! no loops (no for keyword)):

    >>> zip(*x)[0]
    (1, 4, 7)
    >>> zip(*x)[1]
    (2, 5, 8)
    >>> zip(*x)[2]
    (3, 6, 9)
    

    Or list comprehensions:

    >>> x = [ [1,2,3], [4,5,6], [7,8,9] ]
    >>> l = [var[1] for var in x]
    >>> l
    [2, 5, 8]
    

    If you wanted some other index:

    >>> [var[0] for var in x]
    [1, 4, 7]
    >>> [var[2] for var in x]
    [3, 6, 9]