# 从0开始的Python学习003序列

sequence 序列

tuple（定值表； 也有翻译为元组） 和 list (表)。

```a1 = (1,2,3,4,'5',True)

a2 = [6,'7',False]

print(a1,type(a1))

print(a2,type(a2))```

tuple()和list[]的主要区别在于，一旦建立，tuple的各个元素不可再变更，而list的各个元素可以再变更。

```a1 = (1,2,3,4,'5',True)

a2 = [6,'7',False]

print(a1,type(a1))

print(a2,type(a2))

#一个序列作为另一个序列的元素
a3 = [1,[2,3]]

#空序列
a4 = []

print(a3,type(a3))

print(a4)```

```a1 = (1,2,3,4,'5',True)

a2 = [6,'7',False]

print(a1,type(a1))

print(a2,type(a2))

#一个序列作为另一个序列的元素
a3 = [1,[2,3]]

#空序列
a4 = []

print(a3,type(a3))

print(a4)

print('============分割线=============')

print('数组[下标]')

print(a1[0])

print(a3[1])

#元素的变更

a2[0] = 9

print(a2)

#如果是tuple进行修改的时候会报错
a1[0] = 9

print (a1)```

### 其他引用方式

print(a1[:5])             # 从开始到下标4 （下标5的元素 不包括在内）

print(a1[2:])             # 从下标2到最后

print(a1[0:5:2])          # 从下标0到下标4 (下标5不包括在内)，每隔2取一个元素 （下标为0，2，4的元素）

print(a1[2:0:-1])         # 从下标2到下标1

print(a1[-1])             # 序列最后一个元素

print(a1[-3])             # 序列倒数第三个元素

```Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
>>> print(1)
1
>>>
==================== RESTART: E:/python/studyPython004.py ====================
5
>>>
==================== RESTART: E:/python/studyPython004.py ====================
(1, 2, 3, 4, '5', True) <class 'tuple'>
[6, '7', False] <class 'list'>
>>>
==================== RESTART: E:/python/studyPython004.py ====================
(1, 2, 3, 4, '5', True) <class 'tuple'>
[6, '7', False] <class 'list'>
[1, [2, 3]] <class 'list'>
[]
>>>
==================== RESTART: E:/python/studyPython004.py ====================
(1, 2, 3, 4, '5', True) <class 'tuple'>
[6, '7', False] <class 'list'>
[1, [2, 3]] <class 'list'>
[]
============分割线=============
1
[2, 3]
Traceback (most recent call last):
File "E:/python/studyPython004.py", line 29, in <module>
a1[0] = 9
TypeError: 'tuple' object does not support item assignment
>>>
==================== RESTART: E:/python/studyPython004.py ====================
(1, 2, 3, 4, '5', True) <class 'tuple'>
[6, '7', False] <class 'list'>
[1, [2, 3]] <class 'list'>
[]
============分割线=============

1
[2, 3]
[9, '7', False]
Traceback (most recent call last):
File "E:/python/studyPython004.py", line 36, in <module>
a1[0] = 9
TypeError: 'tuple' object does not support item assignment
>>>
==================== RESTART: E:/python/studyPython004.py ====================
(1, 2, 3, 4, '5', True) <class 'tuple'>
[6, '7', False] <class 'list'>
[1, [2, 3]] <class 'list'>
[]
============分割线=============

1
[2, 3]
[9, '7', False]
3
>>> ```

str = 'abcdef'

print(str[2:4])

36 篇文章12 人订阅

0 条评论