Sample usage of Python list slices

  • 2020-05-30 20:28:58
  • OfStack

This article illustrates the use of Python list slices as an example. I will share it with you for your reference as follows:

Slicing (slice) is supported for sequenced ordered sequences in Python, such as lists, strings, tuples.

Format: [start:end:step]

start: start index, starting at 0 and ending at -1

end: end of index

step: step length, end-start, step length is positive, value from left to right. When the step size is negative, the value is reversed

Note that the result of the slice contains no closing index, that is, no last bit, and -1 represents the last position index of the list

b1=a[:] # Omitting all, representing the interception of all content, can be used to 1 The list is copied to another 1 A list of 

Results: [1, 2, 3, 4, 5, 6]

b=a[0:-1:1] # From the position 0 Start to finish, increase each time 1 And interception. Does not contain the end index location 

Results: [1, 2, 3, 4, 5]

c1=a[:3] # Omit the index of the starting position, as well as the step size. The default starting position is to start from scratch, and the default step size is 1 , ending the position index as 3

Results: [1, 2, 3]

c=a[0:5:3] # From the first 1 Position to the left position, each 3 A take 1 A value 

Results: [1, 4]

d=a[5:0:-1] # Reverse the values 

Results: [6, 5, 4, 3, 2]


Results: [6, 5, 4, 3, 2, 1]

For more information about Python, please check out the topics on this site: Python data structure and algorithm tutorial, Python Socket programming skills summary, Python function skills summary, Python string manipulation skills summary, Python introduction and advanced classic tutorial and Python file and directory manipulation skills summary.

I hope this article is helpful to you Python programming.

Related articles: