Operation of the python--list

Source: Internet
Author: User
Tags iterable

List operations: Verbose + error-prone
Suppose there are two lists:
List1 = [A]
list2 = [' A ', ' B ', ' C '] list of operations:


1.list.append ()
Append only accepts one parameter
Append can only add elements at the end of the list and cannot select locations to add elements.
The following actions can be seen
>>> List1 = [+]
>>> list1.append (4)
>>> List1
[1, 2, 3, 4]
>>> list2 = [' A ', ' B ', ' C ']
>>> List2.append (d)//Add string to "
Traceback (most recent):
File "<stdin>", line 1, in <module>
nameerror:name ' d ' is not defined
>>> list2.append (' d ')
>>> List2
[' A ', ' B ', ' C ', ' d ']


2.list.extend ()
The Extend () method takes a list as an argument and adds each element of the parameter to the end of the original list.
If you add elements with extend (), you need to have the same type of elements as the original list, not very useful, if you need to add elements, use append better.
>>> list1.extend (list2)
>>> List1
[1, 2, 3, 4, ' A ', ' B ', ' C ', ' d ']
>>> list2 = [' A ', ' B ', ' C ']
>>> List1 = [+]
>>> list1.extend (' a ')
>>> List1
[1, 2, 3, ' a ']
>>> list2.extend (1)//Cannot add a number, the number is int
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: ' int ' object is not iterable
>>> list2.extend (' 1 ')//can add a string
>>> List2
[' A ', ' B ', ' C ', ' 1 ']
>>> list2.extend (int (1))
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: ' int ' object is not iterable
>>> list2 = [' A ', ' B ', ' C ']
>>> list2.append (1)
>>> List2
[' A ', ' B ', ' C ', 1]


3.list.insert ()
Insert () accepts two parameters, insert (insert position, insert Element) the insertion position starts at 0, and the inserted element precedes the first. Insert (I,X) I starting from 0, element x is inserted in front of I.
>>> num = [0,1,2,3]
>>> num.insert (0, ' a ')//insert as No. 0 element, starting from 0
>>> num
[' A ', 0, 1, 2, 3]//insert in front of the No. 0 element

Operation of the python--list

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.