"Python" slice

Source: Internet
Author: User

Some of the elements that work with python, called slices.

Create slices

Specifies the index of the first element and the last element to use, like the range () function, where Python stops after reaching the element that precedes the second index you specify.

Define a list first vegetables

vegetables = ['tomato','bean','potato ','onion','radish']

Take the 1th to 3rd element out of the

Print (Vegetables[0:3])

Take the 2nd to 4th element out of the

Print (Vegetables[1:4])

Remove the first 4 elements

Print (Vegetables[:4])

Remove all elements after the 2nd element (including 2nd)

Print (vegetables[2:])

Remove the last three elements

Print (vegetables[-3:])
Copy List

To copy a slice, create a slice that contains the entire list by omitting both the start index and the Terminate index [:], which allows Python to create a slice that starts with the first element and terminates at the last element, that is, copying the entire list.

Fruits = ['aplle','pear','lemon' ,'peach'= fruits[:]print(fruitsfoot_ Copy

Perhaps from the above case we have no way to see that there are 2 lists, the following example can better explain

Fruits = ['Aplle','Pear','Lemon','Peach']fruits_copy=Fruits[:]fruits.append ('Grape') Fruits_copy.append ('Banana')Print(fruits)Print(fruits_copy)

Printing results:

[' Aplle ', ' pear ', ' lemon ', ' peach ', ' grape ']
[' Aplle ', ' pear ', ' lemon ', ' peach ', ' banana ']

This means that the list is indeed copied.

The following is a wrong case

 fruits = [ " aplle  " ,  " pear  " ,  " lemon   ", "  peach  Span style= "COLOR: #800000" > " ]fruits_copy  =  fruits  
fruits.append ('grape') fruits_copy.append ('Banana  ')print(fruits)print(fruits_copy)

Printing results:

[' Aplle ', ' pear ', ' lemon ', ' peach ', ' grape ', ' banana ']
[' Aplle ', ' pear ', ' lemon ', ' peach ', ' grape ', ' banana ']

This assigns the fruits to fruits_copy instead of storing the fruits copy to the fruits_copy.

"Python" slice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.