Search code examples
pythonlistslicedel

Slicing List Confusion in Python


Alright, I am super new to Python and something is bugging me about slicing lists. Why is it that I get [1, 3, 4] back when I am slicing [1] and [3] from this code?

z = [1, 2, 3, 4, 5]
del z[1], z[3]
print z

I assumed i would be getting [1, 3, 5] back since it appears [2] and [4] are being removed.

if-->[1, 2, 3, 4, 5]
is-->[0, 1, 2, 3, 4]

Where is it that my logic is getting messed up?


Solution

  • The first deletion changes the list indices, so the next one isn't where it was before... Simplified

    >>> a = [1, 2, 3]
    >>> del a[0] # should delete 1
    >>> a
    [2, 3]
    >>> del a[1] # This use to be the index for 2, but now `3` is at this index
    >>> a
    [2]