[ ]
,其中元素之間使用逗號,
分隔,列表中各個元素的資料型別可以不同,例如:
lis1 = ['a', 'b', 2000, 2019]
list2 = [1, 2, 3, 4, 5]
print(list2[1:3])
Python 中所有基於範圍的語法都遵循“左閉右開”原則,即起始下標對應的元素被包含在內,範圍內最後一個元素是結束下標對應的元素之前的元素。
>>> lis1 = ['a', 'b', 2000, 2019]
>>> list2 = [1, 2, 3, 4, 5]
>>> print(list2[1:3])
[2, 3]
print(list2[-2:])
上述程式碼的執行結果如下所示:
>>> lis1 = ['a', 'b', 2000, 2019]
>>> list2 = [1, 2, 3, 4, 5]
>>> print(list2[1:3])
[2, 3]
>>> print(list2[-2:])
[4, 5]
list2[2] = 6
print(list2)
>>> lis1 = ['a', 'b', 2000, 2019]
>>> list2 = [1, 2, 3, 4, 5]
>>> print(list2[1:3])
[2, 3]
>>> print(list2[-2:])
[4, 5]
>>> list2[2] = 6
>>> print(list2)
[1, 2, 6, 4, 5]
list2[2:4] = ['C', 'D', 'E']
print(list2)
>>> lis1 = ['a', 'b', 2000, 2019]
>>> list2 = [1, 2, 3, 4, 5]
>>> print(list2[1:3])
[2, 3]
>>> print(list2[-2:])
[4, 5]
>>> list2[2] = 6
>>> print(list2)
[1, 2, 6, 4, 5]
>>> list2[2:4] = ['C', 'D', 'E']
>>> print(list2)
[1, 2, 'C', 'D', 'E', 5]
list2[3:4] = [ ]
print(list2)
>>> lis1 = ['a', 'b', 2000, 2019]
>>> list2 = [1, 2, 3, 4, 5]
>>> print(list2[1:3])
[2, 3]
>>> print(list2[-2:])
[4, 5]
>>> list2[2] = 6
>>> print(list2)
[1, 2, 6, 4, 5]
>>> list2[2:4] = ['C', 'D', 'E']
>>> print(list2)
[1, 2, 'C', 'D', 'E', 5]
>>> list2[3:4] = [ ]
>>> print(list2)
[1, 2, 'C', 'E', 5]
list2[:] = []
a = ['a', 'b', 'c']
b = [1, 2, 3]
x = [a, b]
print(x)
>>> a = ['a', 'b', 'c']
>>> b = [1, 2, 3]
>>> x = [a, b]
>>> print(x)
[['a', 'b', 'c'], [1, 2, 3]]
a = ['a', 'b', 'c']
del a
print(a)
>>> a = ['a', 'b', 'c']
>>> del a
>>> print(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
print(a)
NameError: name 'a' is not defined
運算子 | 表示式 | 結果 | 描述 |
---|---|---|---|
+ | [1, 2, 3]+[4, 5, 6] | [1, 2, 3, 4, 5, 6] | 組合 |
* | ['Hi!']*4 | ['Hi!', 'Hi!' , 'Hi!', 'Hi!'] | 重複 |
in | 3 in [1, 2, 3] | True | 元素是否存在於列表中 |