List
1.1 Create a list
>>number = [1,2,3]
>>mix = [1,"中文",3.14,[1,2,2]]
>>empty = []
1.2 add an element to the list
1.2.1 append () method
>>number = [1,2,3]
>>number.append(4)
>>number
[1,2,3,4]
1.2.2 extend () method
Use a list to another list extension, its argument must be a list.
1.3 Python list of functions & methods
Python includes the following functions:
No. | function |
---|---|
1 | len (list) listing the number of elements |
2 | max (list) returns a list of the maximum element |
3 | min (list) returns a list of the minimum element |
4 | list (seq) converts a list of tuples |
Python includes the following methods:
No. | method |
---|---|
1 | list.append (obj) add new objects in the end of the list |
2 | list.count (obj) count the number of an element that appears in the list |
3 | list.extend (seq) disposable plurality of values is added at the end of the other sequence list (list with a new original extended list) |
4 | list.index (obj) to find the location of an index value of the first match from the list |
5 | list.insert (index, obj) the objects into the list |
6 | list.pop (obj = list [-1] ) removes an element in the list (default to the last element), and returns the value of the element |
7 | list.remove (obj) to remove the list a value of the first match |
8 | list.reverse () reverse elements in the list |
9 | list.sort ([func]) to sort the list of the original |
10 | list.clear () Clear List |
11 | list.copy () copy list |
Tuple
Python is similar to a list of tuples, except that the elements of the tuple can not be modified.
Tuples use parentheses, square brackets list.
Tuple create very simple, only need to add elements in parentheses and separated by commas can be.
>>>tup1 = ('Google', 'Runoob', 1997, 2000);
>>> tup2 = (1, 2, 3, 4, 5 );
>>> tup3 = "a", "b", "c", "d"; # 不需要括号也可以
>>> type(tup3)
<class 'tuple'>
Empty tuples: tup = ()
Special attention: tuple contains only one element needs to be added after the element commas, brackets or operator will be used as:
>>>tup1 = (50)
>>> type(tup1) # 不加逗号,类型为整型
<class 'int'>
>>> tup1 = (50,)
>>> type(tup1) # 加上逗号,类型为元组
<class 'tuple'>