Sequence 序列
a sequence means a data container that has content is continuous and ordering, having index.

Slicing 切片
Means that, it get a Subsequence 子序列 from a sequence.
Ex: a list, tuple, string, etc that support slicing operation
Syntax
py
sequence[start_items : end_items : step]Info
- Step = 1 (default value), means that operation is
1 by 1 - Step = 2, means that operation will always
skip1 - Step = n, means that operation will always
skipn-1 - if step is negatives value, Its start from right to left (Reversed).
Also, with slicing operation will get an new sequence instead of modify it
Usage
sequence-slicing.py
py
# List
list_list = [0, 1, 2, 3, 4, 5, 6]
# index: 0 1 2 3 4 5 6
# Slicing:
# 1. From 1 to 4, step = 1 (can be ignored)
print(list_list[1:4:1]) # Expected: [1, 2, 3]
# Without step
print(list_list[1:4]) # Expected: [1, 2, 3]
# Tuple
tuple_list = (0, 1, 2, 3, 4, 5, 6)
# 2. from 0 to end, 7th item , step = 1 (can be ignored)
# 7 - 0 = 7 items.
print(tuple_list[0:7:1]) # (0, 1, 2, 3, 4, 5, 6)
# For starting to end can use:
print(tuple_list[:]) # (0, 1, 2, 3, 4, 5, 6)
# String
str_dc = "0123456789"
# Slicing From start to end step = 2
print(str_dc[::2]) # 02468
# Using negative step, -1 (Reversed)
print(str_dc[::-1]) # 9876543210
# Negative step, -2
print(str_dc[::-2]) # 97531Output:
[1, 2, 3]
[1, 2, 3]
(0, 1, 2, 3, 4, 5, 6)
(0, 1, 2, 3, 4, 5, 6)
02468
9876543210
97531Comprehensive Example
Given:
py
text = str("Hi, I'm John and he is Will")- Define an original text
- Make text in reversed style.
- Get John in a original style and print it on console.
sequence-slicing-ex.py
py
# Define an original text
text = str("Hi, I'm John and he is Will")
# Make text in reversed style.
reversed_text = text[::-1]
print(reversed_text) # lliW si eh dna nhoJ m'I ,iH
# Get John in a original style
split_reversed_text = reversed_text.split()
splited_john = split_reversed_text[-3]
print(splited_john[::-1]) # JohnOutput:
lliW si eh dna nhoJ m'I ,iH
John