Home > Software engineering >  How slicing works when step is given separately?
How slicing works when step is given separately?

Time:09-22

I have a list object which looks as below:

lst = [50,34,98,8,10]

The output for the statement print(lst[::][::-1][::-1][::-1][::-1]) is as below:

lst = [50,34,98,8,10]

Please help me understand how slicing works when step is given separately

CodePudding user response:

Explanation:

  1. You first do lst[::] which is just getting the whole list, it processes it to be lst[::1] which gives:

    >>> lst[::1]
    [50, 34, 98, 8, 10]
    >>> 
    
  2. You're then reversing the list times, but 4 is even so it doesn't get reversed at all:

    >>> lst[::-1]
    [10, 8, 98, 34, 50]
    >>> lst[::-1][::-1]
    [50, 34, 98, 8, 10]
    >>> lst[::-1][::-1][::-1]
    [10, 8, 98, 34, 50]
    >>> lst[::-1][::-1][::-1][::-1]
    [50, 34, 98, 8, 10]
    >>> 
    
  • Related