Search code examples
python-3.xprogram-slicing

Nested List using indexing and slicing


How do I slice or index this list in order to get the answer below? I've tried doing multiple methods of slicing and nothing has worked for me.

L = [0, [], [1,2,3,4], [[5],[6,7]], [8,9,10]]
newL = [L[0],L[2][1],L[2][2],L[3][0]] 

Answer: [0, 2, 3, [5 ,6], 8, 10]

newL is what I have so far, but I can't seem to get the [6,7] split in the nested list.


Solution

  • We start with:

    L = [0, [], [1, 2, 3, 4], [[5], [6, 7]], [8, 9, 10]]
    

    We want:

    [0, 2, 3, [5, 6], 8, 10]
    

    Let's start from the farthest inside. We need [5, 6]. These are both buried:

    >>> L[3][0][0]
    5
    >>> L[3][1][0]
    6
    >>> [L[3][0][0], L[3][1][0]]
    [5, 6]
    

    One layer farther out we need 2, 3:

    >>> L[2][1]
    2
    >>> L[2][2]
    3
    

    Now put it together:

    >>> [L[0], L[2][1], L[2][2], [L[3][0][0], L[3][1][0]], L[4][0], L[4][2]]
    [0, 2, 3, [5, 6], 8, 10]