1

What's the difference between [:5] and [5] in this Python code?

y_test_predicted = model.predict(X_test)

residuals = Y_test   -   y_test_predicted

print(residuals[:5])

print(residuals[5])
quamrana
  • 37,849
  • 12
  • 53
  • 71
God_is
  • 21
  • 1
  • 4
  • 4
    You need to take a few steps back and study basic Python syntax and list *slicing*. Please take some time with the excellent [Python documentation](https://docs.python.org/3/). – Some programmer dude Sep 08 '20 at 08:23
  • 1
    `5` is just an index, `:5` is a *slice*, see e.g. https://stackoverflow.com/questions/509211/understanding-slice-notation. – jonrsharpe Sep 08 '20 at 08:27
  • 1
    Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – hdost Sep 08 '20 at 10:46
  • Not all use cases require to really learn Python. I wanted to translate python algorithms to Javascript with a package `opencv4nodejs` that execute compiled c++ code. When I see `cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]`, I already know intuitively to use `Array.prototype.sort` and `Array.prototype.reverse` if necessary. But `[:5]` is not intuitive to go for `Array.prototype.slice` or `Array.prototype.splice`. If I want to translate more complex codes, I would rather learn Python fully and switch directly to Python instead. – KeitelDOG Mar 26 '21 at 17:28

1 Answers1

3

you can find a useful information about slicing in this link.

Refer to below simple example to understand it as a glimpse:

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j']
print(list[5]) #it will print: f
print(list[:5]) #it will print:  ['a', 'b', 'c', 'd', 'e'], indices form 0 to 4
#List Slicing: list[start:stop:step]
Pooria_T
  • 136
  • 1
  • 7