Analysis of Slicing and Copying Examples of python List

  • 2021-12-05 06:29:56
  • OfStack

You can refer to the python slice copy list of knowledge points to explain this content in detail, and have an understanding of the usage of knowledge points

Slicing, that is, processing part of the data in a complete list.

Syntax Variable [Start Index: End Index: Step Size]

First create a list of 1 strings


>>> cars = ['toyota', 'honda', 'mazda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu']
>>> 
>>> cars
['toyota', 'honda', 'mazda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu']

View only the first 3 elements of the list


>>> print(cars[0:3])
['toyota', 'honda', 'mazda']

You can also not specify the starting index bit, which starts from 0 by default


>>> print(cars[:3])
['toyota', 'honda', 'mazda']

View elements 3 through 5 of the list


>>> print(cars[2:6])
['mazda', 'nissan', 'mitsubishi', 'subaru']

View the value from the third to the end of the list, do not specify the termination index bit, and default to the end of the list


>>> print(cars[2:])
['mazda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu']

From the above two examples, we can see that slicing follows the principle of "wrapping header without wrapping tail",

Print all values of the list with step size 2


>>> print(cars[::2])
['toyota', 'mazda', 'mitsubishi', 'suzuki']

Copy 1 copy of cars list data to vivi list


>>> vivi = cars[:]
>>> 
>>> vivi
['toyota', 'honda', 'mazda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu']
>>> 
>>> del cars
>>> 
>>> vivi
['toyota', 'honda', 'mazda', 'nissan', 'mitsubishi', 'subaru', 'suzuki', 'isuzu']

Related articles: