The use of the Python 2.7 Learning notes List

Source: Internet
Author: User
Tags sorts

Like other programming languages, Python also provides a rich data structure to facilitate the processing of data. This article describes two of the most basic collections of data, the use of lists and tuples.

I. Introduction to the use of the list

Can be understood as an ordered sequence. Examples of how to use them are:

List=[] #定义了一个空的列表
List.append ("Hello1") #往列表的尾部插入一个元素
List.append #往列表的尾部插入一个元素, it can be seen that the elements in the list can be of multiple types
Print List
For item in list: #利用for循环遍历列表中的元素
Print Item
List.insert (0,10) #往列表中插入元素, the first parameter of the Insert method is the position that represents the insertion, and 0 indicates the first position
List.insert (2,11)
Print List
The List.pop () #pop方法是移除列表中的元素 (the default is the last one) and returns the element. Note If the list is empty at this point, the exception is thrown
Print List
List.pop (0) #带参数的pop放啊是移除指定位置的元素 and returns the element. Note that if the specified primary element does not exist, the exception is thrown
Print List
List.remove ("Hello1") #remove方法, is the element that deletes the element contents of the list with the parameter, and throws an exception if the element of the specified content does not exist
Print List
The code above demonstrates how to use the Append, insert, pop,remove of the list to insert and delete list elements, and shows how to iterate through the list elements with a for loop. Four.

In addition to the above operation, there are other actions:

1. Built-in function Len, max, Min ,List,del

The first three Python built-in functions are used to get the number of elements in the list, the maximum and minimum values of the elements in the list. Examples are as follows:

>>> list=[12,'ad', []>>> len (list)3>>> max (list) ' AD '>>> min (list)12

Note that if there are no elements in the list, the Len method returns 0, but the Max and Min methods report an exception.

The list method is to convert tuples to list, as described in the next article on tuples.

Del is a built-in keyword in python that you can use to delete variables. You can also use the element in the delete list.

For example: Del list[1] #删除列表第2个元素

Del list[:]

This is to delete all the elements of the list, note that list=[] does not achieve this effect, because there may be other variables that the list points to to it, it just changes the current list variable point, but del list[:] is to delete all the elements in the actual listing

[:] This colon can be added before and after the range, you can delete the specified range of elements, this specific use can be seen in the following list of sharding operations, here is not more introduction.

2, the index method of the list

Used to find the position of the specified value matching element from the list, or to report an exception if the element does not exist, such as:

>>> list=[12,14]>>> list.index 1>>> list.index(+)Traceback ( Most recent call last):  '<stdin>' in <module>   is  not  in List

As you can see, element 14 exists in the list, so index successfully returns the position of the element in the list. Element 13 does not exist, so the index method reports an exception.

3. The Count method of the list

This method is used to count the number of occurrences of an element in a list. Such as:

>>> list=["a","b"]>>> List.count ("a")1>>> List.count ("C") 0>>> List.append ("a")>>> List.count ("a")2

4. Check if the element exists in the list

Because many methods of the list, such as remove, index, are called when the specified element does not exist, the exception is reported. To avoid exceptions, you need to check that the element exists before calling the appropriate method. The method is implemented as follows:

 >>> print   list[  '      

5, the Extend method of the list
This method is used to add all of the elements in another list one time at the end of the list.

It is different from the two-list connection (via the + operator), and the + operation is to return the new list without changing the original two list, and the Extend method is to modify the contents of the list and add a value to the list.

Examples are as follows:

>>> list1=[1,2,3]>>> list2=[4,5]>>> list = list1+List2>>>Printlist[1, 2, 3, 4, 5]>>>Printlist1[1, 2, 3]>>>Printlist2[4, 5]>>> list =list1.extend (List2)>>>PrintListnone>>>Printlist1[1, 2, 3, 4, 5]>>>Printlist2[4, 5]

As you can see, the Extend method does not have a return value.

6, the reverse method of the list

This method stores the elements in the list in reverse. Examples are as follows:

>>> list=[1,2,3]>>> result = list.reverse ()print  resultnone Print list[3, 2, 1]

It can be noted that the reverse method does not have a return value, it changes the list itself. In fact, the various methods of the list, except the Pop method has the return value, the other method does not return a value.

7. Copy and shard operations for lists

Sometimes we need to copy the list and note that the following is not a copy.

List1 = [A]

List2 = List1

Above, List2 and List1 are actually pointing to the same list, working on any one of List1 or list2, and actually working on the same list.

What we call replication is deep replication, which is the creation of a new list (but the content is the same), and the copied list and the original list are not related after creation.

To make a deep copy, you can do this by slicing the list, which is to get part or all of the list, to form a completely new list, regardless of the original list.

Examples are as follows:

>>> list=[1,2,3,4]>>> Newlist=list[1:3]  # shard operation, take 2nd and 3 elements to form a new list  Print  newlist[2, 3]print  list[1, 2, 3, 4]>>> list.pop ()4>>> newlist.pop ()print  list[1, 2, 3]print newlist[2]

As you can see, the list obtained by The Shard operation is a completely new list, independent of the original list, and the two are completely independent, and the subsequent operations do not affect each other.

The complete syntax for the distinction is: List[startindex:endindex] #其中startindex是起始位置 (0 for the first element) and endindex for the end position (but not the end position).
Here are some special operations for sharding

NewList =list[:] #复制整个列表

NewList = list[2:] # Gets the third and subsequent elements of the list, and returns an empty list if the specified ordinal exceeds the maximum ordinal of the list

Newlist=list[:3] #获取列表的前3个元素, if the specified number exceeds the maximum number of elements in the list, the entire list content is returned

Newlist=list[-2:] # Gets the last 2-bit element of the list, and returns the entire list content if the absolute value of the specified number is greater than the total number of elements in the list

NEWLIST=LIST[-3:-1] # This is the equivalent of moving forward from the back of the list, getting included in the bottom 3rd ~ 2nd element

The Shard operation described above, gets the list is continuous, Python's Shard operation also provides the operation that can specify the step size, that is, the obtained element is not contiguous, but the specified step is skipped to get the element.

To illustrate:

>>> list = [1,2,3,4,5,6,7,8,9]>>> newlist = list[1:6:2]print  newlist [2, 4, 6]>>> newlist = list[1:6:3]print  newlist[2, 5]

Compared to the above code, [:] The last parameter in the operation is the step size.
For example [1:6:2], if the step is 1, then [1:6] Gets the data is 2,3,4,5,6, and here the step is 2, because the first to get the element is 2, the interval of a re-fetch, the result is 2,4,6.

Similarly [1:6:3], where the step is 2, because the first to get the element is 2, the interval of 2 re-fetch, the result is 2, 5.

8. List the Sort method

This method sorts the list from low to high, noting that it does not return a value, and modifies the list itself. Such as:

>>> list=[3,8,9]>>> newlist=print  list[3, 8, 9]  Print  newlistnone>>> list.reverse ()  print  list[9, 8, 3]

The above example also takes advantage of the reverse method, and finally gets a list of sorts from high and low.

9, the list of advanced sorting

The sort method can only be ordered by default, by specifying a sorting algorithm (function), which is ordered according to its own requirements.

is to specify a sort function for the sort method. This usage is no longer covered by this article.

Ii. Summary of the use of the list

As can be seen from the above introduction, the operation of the list (including the list itself method and the general built-in function) is still quite a lot of, remember also more troublesome.

For the sake of memory, we summarize here under the description. In general, for a list, there is nothing more than creating, adding and pruning, and several other operations.

1. Create

created directly through [] conformance, can be initialized when created

2. Increase

You can take advantage of append, insert, extend these list methods.

3. Delete

You can use the Pop,remove method of the list and the built-in function del to remove elements from the list.

4, change

You can modify the contents of an element by using a list subscript, such as list[2] =xxx

5. Check

There are several ways to query the elements in a list, as follows:

1) use a For loop to iterate through all the elements in the list

2) Use ordinal index to get the element of the specified ordinal (same as array operation in other languages), such as list[0] gets the 1th element, if the specified index is out of bounds, the exception is reported

3) Use the index method to get the position of the specified element

4) Use the Pop method to get the element to the specified position

5) Using Shard operations to get some or all of the list, this note will result in a new copy of the list part or all

6) Use the In operator to check if an element value exists in the list

6. Other operation

If you sort by using the sort method, the reverse method lists element order reversal, and the Shard operation copies the list.

Use the built-in function len,max,min to get the number of elements in the queue, the maximum, the minimum value.

Use the Count method to find the number of occurrences of the specified element in the queue.

The use of the Python 2.7 Learning notes List

Related Article

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: 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.