All the ways to manipulate a list in Python

Source: Internet
Author: User

List:

names = ['a','b','c',' D ']

1, Append: Names.append ()

>>> names.append ('e')>>> names['A  'b'c'd ' ' e ']

2. Delete: Pop,remove,del

1) Pop ()

>>> names.pop ()'e'

If no subscript is specified, the last element is deleted by default

>>> Names.pop (2)'C'

When you specify subscript, the element corresponding to the subscript is deleted

2) Remove ()

>>> names.remove ('e')>>> names['A  'b'c'd ']

3) Del

>>> del names[4]>>> names['a' b ' ' C ' ' D ']

3. Find the Element location: index ()

>>> names.index ('C')2

4. Number of statistics elements: count ()

>>> names.append ('d')>>> names.count ('d ' )2

5. Inversion: Reverse ()

>>> names.reverse ()>>> names['d'C  'b'a']

6. Empty: Clear ()

>>> names.clear ()>>> names[]

7. Insert: Insert ()

>>> Names.insert (2,'devilf')>>> names[ ' a ' ' b ' ' Devilf ' ' C ' ' D ']

There are other ways to insert:

>>> names[3'LeBron'>>> names['a ' ' b ' ' Devilf ' ' LeBron ' ' D ']

8. Sort: Sort () sorted by ASCII code

>>> Names.insert (4,'&&')>>>names['a','b','D','Devilf','&&','LeBron']>>>Names.sort ()>>>names['&&','a','b','D','Devilf','LeBron']

9, stitching two list: Extend ()

>>>names.extend (place)>>>names['&&','a','b','D','Devilf','LeBron','Beijing','Shandong','USA']

10. Slicing the list

1) List all the elements

>>>names[::]['&&','a','b','D','Devilf','LeBron','Beijing','Shandong','USA']

2) List the last element, starting at the middle position, listing all the elements behind

>>> names[-1]'USA'
int (Len (names)/2)>>> names[a:]['devilf ' LeBron ' ' Beijing ' ' Shandong ' ' USA ']

11. Copy: Copy ()

>>>names.copy () ['&&','a','b','D','Devilf','LeBron','Beijing','Shandong','USA']

All the ways to manipulate a list in Python

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.