What does this line of code mean (python): L [::2], L [1::2] = L [1::2], L [::2]?
When it comes to lists in python or accessing arrays, this is the general syntax:
- list_elements[startAt:endBeforeThisPosition:skipInterval]
- # startAt -> if not provided, it starts at 0
- # endBeforeThisPosition -> if not provided, it is the last index
- # skipInterval -> if not provided, default is 1 (jump interval)
Therefore, lets take a list as [0,1,2,3,4,5,6,7,8,9]
- L = [0,1,2,3,4,5,6,7,8,9]
- # Following the default usage of list accessing or slicing
- L [::] # start at the beginning of the list
- # end at the last element
- # jump in intervals of 1
- # answer is [0,1,2,3,4,5,6,7,8,9]
Another way to access everything without using the :: notations is to use what we call the Python Ellipsis object (...) which I have written about here in a previous post
Thus L […] is the same a writing L[::]
However, you must make sure the L is an array such as a numpy array for this to be able to work our well. Else you will get an error as such
To do this, follow
- import numpy as np
- new_L = np.array(L)
- L[...] # answer is [0,1,2,3,4,5,6,7,8,9]
Now to the answers to your questions
- L [::2] # start at the beginning of the list
- # end at the last element
- # jump in intervals of 2
- # answer is [0, 2, 4, 6, 8]
- # Remember array indexing always starts from 0
- # so it is always like [0,1,2,3,4,5,6,...]
- L [1::2] # start at the 2nd element of the list (number 1)
- # end at the last element
- # jump in intervals of 2
- # answer [1, 3, 5, 7, 9]
You can find some more examples / variations and uses from this informative website.