Casa > W > What Does This Line Of Code Mean (Python): L [::2], L [1::2] = L [1::2], L [::2]?

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:

  1. list_elements[startAt:endBeforeThisPosition:skipInterval] 
  2.  
  3. # startAt -> if not provided, it starts at 0 
  4. # endBeforeThisPosition -> if not provided, it is the last index 
  5. # 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]

  1. L = [0,1,2,3,4,5,6,7,8,9] 
  2.  
  3. # Following the default usage of list accessing or slicing 
  4. L [::] # start at the beginning of the list 
  5. # end at the last element 
  6. # jump in intervals of 1 
  7. # 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

main-qimg-6a60c269169e56dfbf41312effb893aa

To do this, follow

  1. import numpy as np 
  2. new_L = np.array(L) 
  3. L[...] # answer is [0,1,2,3,4,5,6,7,8,9] 

Now to the answers to your questions

  1. L [::2] # start at the beginning of the list 
  2. # end at the last element 
  3. # jump in intervals of 2 
  4. # answer is [0, 2, 4, 6, 8] 
  5.  
  6. # Remember array indexing always starts from 0 
  7. # so it is always like [0,1,2,3,4,5,6,...] 
  8. L [1::2] # start at the 2nd element of the list (number 1) 
  9. # end at the last element 
  10. # jump in intervals of 2 
  11. # answer [1, 3, 5, 7, 9] 

You can find some more examples / variations and uses from this informative website.

De Lunt

O que significa "rodar uma matriz" na programação? :: Você só pode converter um array de tamanho 1 para um escalar Python?