AdSense

網頁

2020/12/7

Python List 基本用法範例

Python的List的基本用法如下。

int_list = [1, 2, 3, 4, 5]
print(int_list)  # [1, 2, 3, 4, 5]
print(int_list[0])  # 1
print(int_list[1])  # 2
print(int_list[-1])  # 5
print(int_list[-2])  # 4
print(int_list[2:4])  # [3, 4]
print(int_list[0:5:2])  # [1, 3, 5]
print(int_list[:2])  # [1, 2]
print(int_list[2:])  # [3, 4, 5]

int_list.append(6)
print(int_list)  # [1, 2, 3, 4, 5, 6]

int_list.insert(3, 13)
print(int_list)  # [1, 2, 3, 13, 4, 5, 6]

int_list.remove(13)
print(int_list)  # [1, 2, 3, 4, 5, 6]

int_list.extend([21, 22, 23])
print(int_list)  # [1, 2, 3, 4, 5, 6, 21, 22, 23]

print(int_list.pop())  # 23
print(int_list)  # [1, 2, 3, 4, 5, 6, 21, 22]

int_list[5:] = []
print(int_list)  # [1, 2, 3, 4, 5]

print(int_list.count(3))  # 1

print(len(int_list))  # 5

int_list.reverse()
print(int_list)  # [5, 4, 3, 2, 1]

str_list = ['a', 'b', 'c']
print(str_list)  # ['a', 'b', 'c']

str_list = str_list + ['d', 'e']
print(str_list)  # ['a', 'b', 'c', 'd', 'e']

str_list[1:3] = ['x', 'y']
print(str_list)  # ['a', 'x', 'y', 'd', 'e']

empty_list = []
print(empty_list)  # []
# print(empty_list[0])  # IndexError: list index out of range

for迴圈遍歷List。

int_list = [1, 2, 3, 4, 5]

for n in int_list:
    print(n)

印出結果如下。

1
2
3
4
5


沒有留言:

AdSense