[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.

[Python] What is a slice? An easy-to-understand explanation of the meaning and usage with actual examples

Slices you hear when you're learning python.

Because the behavior changes depending on the range specification and the amount of change specified by plus and minus.

Check each pattern to see what happens when the range is specified, the amount of change is set to plus or minus, or when the range is specified outside the range, and unintended behavior is prevented.


**table of contents**
  1. [What is a slice? ](# 1-What is a slice)
  2. Slice Basic Syntax (# 2-Slice Basic Syntax)
  3. [How to read the sequence number](# 3-How to read the sequence number)
  4. [Starting value is positive](# 1 When starting value is positive)
  5. [list type](# 1-1-list type)
  6. [Character](# 1-2-Character)
  7. [Start value is negative](# 2 When the start value is negative)
  8. [list type](# 2-1-list type)
  9. [Character](# 2-2-character)
  10. [Mixed minus and plus](# 3 Mixed minus and plus)
  11. [Concept when specifying outside range](# 4 Concept when specifying outside range)
  12. [Check with examples for each pattern](# 4-Check slices with examples for each pattern)
  13. [[:] Not specified](# 1-All not specified)
  14. [[a:] Specify only start](# 2-a Specify only start)
  15. [[: b] Specify only the end](# 3-b Specify only the end)
  16. [[a: b] Specify start and end](# 4-ab Specify start and end)
  17. [[a: b: c] Specify start, end, change amount](# 5-abc specify start end end change amount)
  18. [[a :: c] Start, specify change amount](# 6-ac Specify start change amount)
  19. [[: b: c] End, specify change amount](# 7-bc Specify end change amount)
  20. [[:: c] Specify only the amount of change](# 8-c Specify only the amount of change)
  21. [Error case](# 5-Error case)

## 1. What is a slice?

A type of ** range specification method ** such as list. Notation to specify the range with [] and :.

Things like [1: 5] and [2:] that you often see in list and for statements.

It can be used not only for list but also for character strings (str), tuples, sets, ranges, etc.

Cut out (slice) consecutive elements and characters at any place.


## 2. Slice basic syntax `[a:b:c]` └ "a": Starting sequence number └ "b": Ending sequence number (less than) └ "c": amount of change
#### ▼ "Minus" can be set for a, b, and c respectively

** Does not include the value specified by "b" **. └ To end with the specified value.


#### ▼ Each element can be omitted
  1. [:]: Not specified = All
  2. [a:]: Specify only the start
  3. [: b]: Specify only the end
  4. [a: b]: Specify start and end
  5. [a: b: c]: Specify start, end, change amount
  6. [a :: c]: Start, specify the amount of change
  7. [: b: c]: End, specify the amount of change
  8. [:: c]: Specify only the amount of change

** Supplement ** 9. [a ::]: Specify only the start (same as [a:]) 10. [: b:]: Specify only the start (same as [: b])


## 3. How to read the sequence number The allocation of array numbers changes depending on whether the starting value is positive or negative **.

(1) When the start value is positive 1-1. List type 1-2. Characters

(2) When the start value is negative 2-1. list type 2-2. Characters

(3) When the start price is minus and the end price is plus

(4) Concept when specifying outside the range


### (1) When the start value is positive ** Count from 0th **.

1-1. List type

Example 1: When ʻa = [1,2,3,4,5]`

data 1 2 3 4 5
Sequence number 0 1 2 3 4

Example 2: When `b = [2020,3,25," year "," month "," day "]`
data 2020 3 25 Year Month Day
Sequence number 0 1 2 3 4 5

#### 1-2. Character (1 element) Example 1: For "This is slice"
data T h i s i s s l i c e
Sequence number 0 1 2 3 4 5 6 7 8 9 10 11 12

Example 2: `d =" This is a "slice". In the case of "`
data This Re But Su La I Su so Su
Sequence number 0 1 2 3 4 5 6 7 8 9 10 11 12 13

### (2) When the start value is negative ** Count the last data as "-1" th **.

2-1. list type

Example 1: When ʻa = [1,2,3,4,5]`

data 1 2 3 4 5
Sequence number -5 -4 -3 -2 -1

Example 2: When `b = [2020,3,25," year "," month "," day "]`
data 2020 3 25 Year Month Day
Sequence number -6 -5 -4 -3 -2 -1

#### 2-2. Character (1 element) Example 1: When `c =" This is slice "`
data T h i s i s s l i c e
Sequence number -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Example 2: `d =" This is a "slice". In the case of "`
data This Re But Su La I Su so Su
Sequence number -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

### (3) Minus and plus are mixed

** ■ Way of thinking ** Whether it is plus or minus depends on which method ** the number is specified **.

-If it is negative, refer to the data corresponding to the sequence number (-).

-If positive, refer to the data corresponding to the sequence number (+).

data 1 2 3 4 5
Sequence number(+) 0 1 2 3 4
Sequence number(-) -5 -4 -3 -2 -1

** ▼ Example ** ・ Starting value "-3" ⇒ Data is "3" ・ End value "4" ⇒ Data is "5"

⇒ 3 to less than 5. The output is [3, 4].


** ▼ Point ** * `[-3: 4]` does not specify -3 to 4 in succession. It is not "-3, -2, -1,0,1,2,3,4".

If the start and end values are mixed, it is easier to understand by replacing them with positive numbers, which correspond to negative numbers.

・ ` "-3: 4" ` = ` "2: 4" ` ・ ` "-5: 4" ` = ` "0: 4" ` ・ ` "1: -1" ` = ` "1: 5" `


### (4) Concept when specifying outside the range Specifying out of range does not cause an error. The part without data is empty.
## 4. Check the slice for each pattern with an example
  1. [:]: Not specified = All
  2. [a:]: Specify only the start
  3. [: b]: Specify only the end
  4. [a: b]: Specify start and end
  5. [a: b: c]: Specify start, end, change amount
  6. [a :: c]: Start, specify the amount of change
  7. [: b: c]: End, specify the amount of change
  8. [:: c]: Specify only the amount of change

## 1. `[:]` Not specified = All Output all stored data

list (numerical value)


a = [1, 2, 3, 4, 5]
a[:]

#output
# [1, 2, 3, 4, 5]

letter


c = 'This is slice'
c[:]

#output
# 'This is slice'

Character (directly specified)


'This is slice'[:]

#output
# 'This is slice'

## 2. `[a:]`: Specify only the start

▼ Sequence number 2nd or higher (2 to 4)

Designated by plus


a = [1, 2, 3, 4, 5]
a[2:]

#output
# [3, 4, 5]

▼ SEQ ID NO: -4th or higher (-4 to -1)

Specify with minus


a = [1, 2, 3, 4, 5]
a[-4:]

#output
# [2, 3, 4, 5]

** ▼ (Supplement) Sequence number of each data **

data 1 2 3 4 5
Sequence number(+) 0 1 2 3 4
Sequence number(-) -5 -4 -3 -2 -1

#### ■ When out of range is specified -No error will occur. ・ The non-applicable range is empty.

▼ When "6" is specified as the start value in the list that has only "4".

(Outside the range) Designated by plus


a = [1, 2, 3, 4, 5]
a[6:]

#output
# []

No hit


▼ When "-10" is specified as the start value in the list that has only "-5" to "-1" th.

(Outside the range) Specify with minus


a = [1, 2, 3, 4, 5]
a[-10:]

#output
# [1, 2, 3, 4, 5]

The -10 to -6th are empty. -The 5th or higher hit.


## 3. `[: b]` Specify only the end

▼ Sequence number up to 3rd (0 to 2nd) └ Less than 3 (because it ends at the 3rd)

Designated by plus


a = [1, 2, 3, 4, 5]
a[:3]

#output
# [1, 2, 3]

▼ SEQ ID NO: -1st (-5 to -2) └ Less than -1 (because it ends at -1)

Specify with minus


a = [1, 2, 3, 4, 5]
a[:-1]

#output
# [1, 2, 3, 4]

** ▼ (Supplement) Sequence number of each data **

data 1 2 3 4 5
Sequence number(+) 0 1 2 3 4
Sequence number(-) -5 -4 -3 -2 -1

## 4. `[a: b]` Specify start and end

▼ Specify the sequence number from 1st to less than 4. └ 4 is not included (3 elements from 1 to 3)

Designated by plus


a = [1, 2, 3, 4, 5]
a[1:4]

#output
# [2, 3, 4]

▼ SEQ ID NO: -4th to less than -2 └ Does not include -2. (2 elements from -4 to -3)

Specify with minus


a = [1, 2, 3, 4, 5]
a[-4:-2]

#output
# [2, 3]

** ▼ (Supplement) Sequence number of each data **

data 1 2 3 4 5
Sequence number(-) -5 -4 -3 -2 -1

** ■ When the start price is minus and the end price is plus **

If the starting value is negative, refer to ** Data corresponding to sequence number (-) ** for the starting value.

If the closing value is positive, refer to ** Data corresponding to the sequence number (+) ** for the closing value.


** ▼ When -3 is specified for the start value and 4 is specified for the end value **

Designated by plus and minus


a = [1, 2, 3, 4, 5]
a[-3:4]

#output
# [3, 4]

If the start and end values are mixed, it is easier to understand by replacing them with positive numbers, which correspond to negative numbers.

data 1 2 3 4 5
Sequence number(+) 0 1 2 3 4
Sequence number(-) -5 -4 -3 -2 -1

・ ` "-5: 4" ` = ` "0: 4" ` ・ ` "1: -1" ` = ` "1: 5" ` ・ ` "-3: 2" ` = ` "2: 2" `


** ■ When out of range is specified ** No error will occur and the non-applicable data will be empty.

▼ Specify the 10th end value for the data that is only up to the 4th.

Specify out of range (plus)


a = [1, 2, 3, 4, 5]
a[3:10]

#output
# [4, 5]

The sixth and subsequent data are not applicable.


▼ Specify -20 as the start value for the data that is only up to the 5th.

Specify out of range (minus)


a = [1, 2, 3, 4, 5]
a[-20:-3]

#output
# [1, 2]

No hits from -20 to -6th. Data from -5 to less than -3rd is output.


▼ Specify the 10th to 20th data with only 0th to 4th data.

Specify out of range from out of range (plus)


a = [1, 2, 3, 4, 5]
a[10:30]

#output
# []

The output will be empty.


▼ Specify -20 to -10th data with only -1 to -5th data.

Specify out of range from out of range (minus)


a = [1, 2, 3, 4, 5]
a[-20:-10]

#output
# []

The output will be empty.


** ■ When you specify outside the range with plus and minus **

▼ Specify out of range from minus start value to plus end value.

Specify out of range from out of range (minus and plus)


a = [1, 2, 3, 4, 5]
a[-20:10]

#output
# [1,2,3,4,5]

The result is the same as [-5: 4] = [0: 4].

-20 Less than -5 is because there is no data. -5 is the maximum value. -5 corresponds to the 0th designation of plus.

10 Since there is no data after the 4th, 4 is the maximum value.

data 1 2 3 4 5
Sequence number(+) 0 1 2 3 4
Sequence number(-) -5 -4 -3 -2 -1

## 5. `[a: b: c]` Specify start, end, change amount

▼ When the start value 1, end value 9 and change amount 2 are specified.

Specify start, end, change amount(plus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[1:9:2]

#output
# [2, 4, 6, 8]

Increase the sequence number from 1st to 2nd, and execute until less than 9. Extract the data corresponding to the number.


** Specify the amount of change as a minus ** ▼ When the start value is 8, the end value is 3, and the amount of change is -2.

Specify start, end, change amount(minus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[8:3:-2]

#output
# [9, 7, 5]

Decrease the sequence number by 2 from the 8th, and finish when it comes to the 3rd (3rd is not included). Extract the data corresponding to the number.

data 1 2 3 4 5 6 7 8 9 10
Sequence number 0 1 2 3 4 5 6 7 8 9

** All specified as minus ** ▼ When the start value -3, the end value -8, and the amount of change -2 are specified.

Specify start, end, change amount(minus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[-3:-8:-2]

#output
# [8, 6, 4]

Decrease the sequence number by 2 from the 3rd, and finish when it comes to the 8th (-8th is not included). Extract the data corresponding to the number.

data 1 2 3 4 5 6 7 8 9 10
Sequence number -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

## 6. `[a :: c]` Start, specify the amount of change

▼ When the start value 1 and the amount of change 3 are specified

Specify only start and change amount(plus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[1::3]

#output
# [2, 5, 8]

Increase the number from 1st to 3rd and execute until there is data.


▼ When starting value 5 and change amount -1 are specified

Specify only start and change amount(minus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[5::-1]

#output
# [6, 5, 4, 3, 2, 1]

Decrease the number from 5th to 1st, and execute until there is data.


## 7. `[: b: c]` End, specify the amount of change

** Starting value is different ** depending on whether the amount of change is positive or negative.

▼ When the end value 5 and the amount of change 2 are specified (start value 0)

Specify only the end and change amount(plus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[:5:2]

#output
# [1, 3, 5]

** Start value 0th ** Increase the number by 2 and execute to less than 5th (5th is not included).


▼ When the end value 5 and the amount of change -2 are specified (the start value is the last data)

Specify only the end and change amount(plus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[:5:-2]

#output
# [10, 8]

** Start value 9th ** Decrease the number by 2 and execute to less than 5th (5th is not included).


## 8. `[:: c]` Specify only the amount of change

The starting value is different depending on whether the amount of change is ** plus ** or ** minus **.

▼ When the amount of change is positive (starting value 0)

Specify only the amount of change(plus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[::3]

#output
# [1, 4, 7, 10]

** Start value 0th ** Increase the number by 3 and execute until there is data.


▼ When the amount of change is negative (start value is the last data)

Specify only the amount of change(minus)



a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[::-3]

#output
# [10, 7, 4, 1]

** Starting value 1

Decrease the number from 0th ** to 3rd, and execute until there is data.


## 5. Error case There are some objects that cannot be sliced, such as int type (integer) and float type (decimal point).

Error case (int type)


1001[2:]

#output
# TypeError: 'int' object is not subscriptable

Error case (float type)


123.45[2:5]

#output
# TypeError: 'float' object is not subscriptable

[Return to top](#pyhton slice is an easy-to-understand explanation of the meaning and usage)

Recommended Posts

[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.
[Python] Explains how to use the range function with a concrete example
[Python] Explains how to use the format function with an example
A simple example of how to use ArgumentParser
[Python] What is pip? Explain the command list and how to use it with actual examples
python: Tips for displaying an array (list) with an index (how to find out what number an element of an array is)
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
How to convert an array to a dictionary with Python [Application]
[Introduction to statistics] What kind of distribution is the t distribution, chi-square distribution, and F distribution? A little summary of how to use [python]
Python: How to use async with
How to use FTP with Python
Python> What is an extended slice?
[Git] I tried to make it easier to understand how to use git stash using a concrete example
A note on what you did to use Flycheck with Python
How to create a heatmap with an arbitrary domain in Python
How to use an external editor for Python development with Grasshopper
How to utilize Python with Jw_cad (Part 1 What is external transformation)
How to use Python with Jw_cad (Part 2 Command explanation and operation)
[Python] Summary of how to use pandas
[Pandas] What is set_option [How to use]
[python] How to use __command__, function explanation
[Python2.7] Summary of how to use unittest
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
How to use is and == in Python
[Question] How to use plot_surface of python
[Python] What is a formal argument? How to set the initial value
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Introduction to Python] What is the method of repeating with the continue statement?
How to write what to do when an application is first displayed in Qt for Python with Designer
The story of making a tool to load an image with Python ⇒ save it as another name
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
How to read a CSV file with Python 2/3
[Python] How to use two types of type ()
How to crop an image with Python + OpenCV
Summary of how to use MNIST in Python
How to specify attributes with Mock of python
How to use tkinter with python in pyenv
It is more convenient to use csv-table when writing a table with python-sphinx
Creating a Python document generation tool because it is difficult to use sphinx
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
How to save the feature point information of an image in a file and use it for matching
[Python] How to deal with the is instance error "is instance () arg 2 must be a type or tuple of types"
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
How to convert / restore a string with [] in python
A memo connected to HiveServer2 of EMR with python
How to use pip, a package management system that is indispensable for using Python
A memo of how to use AIST supercomputer ABCI
I tried to summarize how to use matplotlib of python
[Python] How to draw a line graph with Matplotlib
How to identify the element with the smallest number of characters in a Python list?
How to write a list / dictionary type of Python3
How to use any or all to check if it is in a dictionary (Hash)
How to use python interactive mode with git bash
How to use Python Kivy ① ~ Basics of Kv Language ~
Usage to call a method of an instance before it is returned by __new__
Basics of Python learning ~ What is a string literal? ~
How to check in Python if one of the elements of a list is in another list
The world's most easy-to-understand explanation of how to make a LINE BOT (1) [Account preparation]