Ways to List Python

Source: Internet
Author: User

1, append

Append new object to end of Word list

>>>lst=[1,2,3]>>>lst.append (4) >>>lst[1,2,3,4]

2. Count

Used to calculate the number of occurrences of an element in a list

>>>[' to ', ' being ', ' or ', ' not ', ' to ', ' being ', ' this ', ' was ', ' a ', ' Question '].count (' to ') 2

3, Extend

Even with a list of B to extend the A list, notice that the a list is changed.

>>>a = [1,2,3]>>>b = [4,5,6]>>>a.extend (b) >>>a[1,2,3,4,5,6]

Similarly, we can use sharding to assign values


4. Index

The index method is used to find a value from the list the first match of the indexed position

>>>lst = [1,2,3,4,5,6]>>>lst.index (3) >>>2


5. Insert

The Insert method is used to insert an object into the list

>>>numbers = [1,2,3,5,6,7]>>>numbers.insert (3, ' four ') >>>numbers[1,2,3, ' Four ', 5,6,7]

Similarly, we can also use Shard assignment to manipulate

Numbers[3:3] = [' Four ']


6. Pop

Pop removes the last element in the list by default, and returns the value of that element, and of course it can use the index.

Note that pop is the only way to modify the list and return the value of the element.


This can be used with inserts, or append, to form a stack, or a queue of data structures.


7. Remove

Remove is used to remove the first occurrence of a value in the list.

>>>x = [' to ', ' is ', ' or ', ' not ', ' to ', ' is ']>>>x.remove (' be ') >>>x[' to ', ' or ', ' not ', ' to ', ' is ' ‘]

Note, remove modifies the list, but does not return a value.


8, Reverse

The reverse method stores the elements in the list in reverse.

>>> x = [1,2,3]>>>x.reverse () >>>x


9. Sort

To sort the list, it is important to note that sort changes the original list. If you need to sort without changing the original list, you need to do the following:

>>>x = [4,5,1,3,2]

>>> y = x[:]

>>>y.sort ()

Note that it is not easy to put y=x, because it points to the same list, and when Y is sort, the original array is still changed.



Ways to List 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.