There is an array with numbers. It is necessary to take away the i-1 from the i-th element and put everything in a separate list.

X = [0, 0.125, 0.25, 0.375] H=[0] for i in X: hk = X[i] - X[i-1] Как быть? H.append(hk) print(H) 
  • What should be with the first element? - Arnial
  • Let it be 0 - Aleksandr Aleksandrov

1 answer 1

for i in in python does not work that way, in i not the element index that is passed, but the element itself.

To obtain an index, use the enumerate function.

enumerate creates a generator that, at each iteration, returns a stupid consisting of the current iteration number and a new item from the list. Simply put, it numbers all the elements of the list.

 X = [0, 0.125, 0.25, 0.375] H = [0] # первый элемент 0 for i, x in enumerate(X[1:]): # проходим по всем элементам кроме первого #enumerate нумерует i от 0 до n где n - длина переданного массива H.append(x - X[i]) # append добавляет 1 элемент в конец списка. 
  • The result was displayed: [0, 0.125, 0.125, 0.125] - Aleksandr Aleksandrov
  • Maybe I misunderstood the problem, but how should it be? - Arnial
  • Is it not [0, 0.125 - 0, 0.25 - 0.125, 0.375-0.25]? - Arnial
  • That's right, this is my blunted. Thank you - Aleksandr Aleksandrov