Two rules when reading Python (slice notation)

This time I will write about Python slice notation.

Slices are written with simple rules, but for beginners If you use it several times, you may get confused at some moments.

At that time, I will talk about two rules that you should be aware of.

■ Two rules when reading slices

① The order of data starts from 0th (basic list) ② The end of the slice will be $ n-1 $, which is one before.

I will explain it with an example.

Prepare the following data. image.png In rule ①, the order is simply 0th, 1st, 2nd, etc. from the first data. Based on that, we will extract the numbers. image.png As mentioned above, we were able to extract numbers based on the index number (ranking starting from 0). With this rule alone, I think it's still easy.

Next, I will explain the rule of ②. This is where the confusing problem arises. image.png In this list, the 5th data from 0 was 10. Even if you specify up to 5th in the slice and extract, only 9 is output.

In this way, in slices, when specifying the range of index numbers Only the order up to $ n-1 $, one step before the end number, is extracted. (This time $ n = 5 $) I will actually put in other numbers and check it. image.png If you are a beginner, you may be conscious of rule (1) and copy sutras while studying. If the above slice notation suddenly appears, you may think it complicatedly.

In that case, please think based on the two rules I mentioned at the beginning.

[Rules for reading slices] ① The order of data starts from 0th ② The end of the slice will be $ n-1 $ image.png

Recommended Posts

Two rules when reading Python (slice notation)
Python slice
python string slice
CRLF becomes LF when reading a Python file
Python slice basics
Use pydantic when reading environment variables in Python
Python3> slice copy / slice notation> used in for statements, etc.
[Note] File reading ~ Python ~
Reading pyc file (Python 3.5.2)
python external file reading
Class notation in Python
[Python] Reading CSV files
[python] Array slice operation
[Python: UnicodeDecodeError] One of the error solutions when reading CSV