序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组。 其他的内建序列有:字符串、Unicode字符串、buffer对象和xrange对象。
序列都可以进行的操作包括 索引, 切片, 加, 乘, 检查成员。
此外,Python已经内置确定 序列 的 长度 以及确定 最大和最小的元素 的方法。
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> a = [1,2,3]
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>>
>>> a = [1,2,3,4]
>>> a.clear()
>>> a
[]
>>>
>>> a = [4,1,2,3]
>>> b = a
>>> b.append(5)
>>> b
[4, 1, 2, 3, 5]
>>> a
[4, 1, 2, 3, 5]
>>>
>>> a = [4,1,2,3]
>>> b = a[:]
>>> b.append(5)
>>> b
[4, 1, 2, 3, 5]
>>> a
[4, 1, 2, 3]
>>>
>>> a = ['a','b','ab',1,2,3]
>>> a.count('a')
1
>>> a.count(1)
1
>>>
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
>>> b
[4, 5, 6]
>>>
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]
>>> b
[4, 5, 6]
>>>
>>> a = [1,2,3,4]
>>> a.index(1)
0
>>> a.index(2)
1
>>> a.index(4)
3
>>> a.index(5)
Traceback (most recent call last):
File "" , line 1, in <module>
a.index(5)
ValueError: 5 is not in list
>>>
>>> a = [1,2,3,5,6,7]
>>> a.insert(3,"four")
>>> a
[1, 2, 3, 'four', 5, 6, 7]
>>> a.insert(7,"eight")
>>> a
[1, 2, 3, 'four', 5, 6, 7, 'eight']
>>>
>>> a = [1,2,3,4,5,6]
>>> a.pop()
6
>>> a
[1, 2, 3, 4, 5]
>>> a.pop(1)
2
>>> a
[1, 3, 4, 5]
>>> a.pop(4)
Traceback (most recent call last):
File "" , line 1, in <module>
a.pop(4)
IndexError: pop index out of range
>>>
>>> a = ["to","be",'or',"not",'to','be']
>>> a.remove('be')
>>> a
['to', 'or', 'not', 'to', 'be']
>>> a.remove('bee')
Traceback (most recent call last):
File "" , line 1, in <module>
a.remove('bee')
ValueError: list.remove(x): x not in list
>>>
>>> a = [1,2,3]
>>> a.reverse()
>>> a
[3, 2, 1]
>>>
>>>
>>> print(reversed(a))
<list_reverseiterator object at 0x035D27D0>
>>> list(reversed(a))
[1, 2, 3]
>>>
>>> a = [1,4,5,6,2,3,4,5]
>>> b = a[:]
>>> b.sort()
>>> b
[1, 2, 3, 4, 4, 5, 5, 6]
>>> a
[1, 4, 5, 6, 2, 3, 4, 5]