特性

  1. Ordered sequence of data (有順序的)
  2. Mutable (可改變的)
  3. Iterable (可疊代的)

List 建立

# List用[]將資料包住,且資料可以任一型態
list1 = []
list2 = list()
print(list1) # []
print(list2) # []
Friends = ['John', 'Mary', 'Alice']
Rand = ['John', 25, 'Tapei']
Matrix = [[1, 2, 3], 4, [5,6]]

#用Type去檢查資料型態
print(type(list1)) # <class 'list'>

List Methods

#元素(elements)有幾個
list3 = ['a', 'b', 'c']
print(len(list3)) # 3

#取出指定index的元素
print(list3[2]) # c
print(list3[-1]) # c
print(list3[0:2]) # ['a', 'b']

#可更改list的內容
list3[0] = 'd'
print(list3) # ['d', 'b', 'c']

#新增
list3.append('f')
print(list3) # ['d', 'b', 'c', 'f']

#插入
list3.insert(1,'g')
print(list3) # ['d', 'g', 'b', 'c', 'f']

#刪除
list4 = ['a', 'b', 'c', 'd']
del list4[1]
print(list4) # ['a', 'c', 'd']

list5 = ['a', 'b', 'c', 'd']
list5.remove('b')
print(list5) # ['a', 'c', 'd']

#移除最後一個元素
list6 = ['a', 'b', 'c', 'd']
list6.pop() # 'd'
print(list6) # ['a', 'b', 'c']

#出現次數
list7 = ['king', 'smith', 'mark', 'smith', 'mark', 'smith']
print(list7.count('smith')) # 3

#排序
list8 = [21, 48, 30, 12, 31, 999, 1]
print(sorted(list8)) # [1, 12, 21, 30, 31, 48, 999]
print(sorted(list8, reverse = True)) # [999, 48, 31, 30, 21, 12, 1]

#字串轉串列
number_word = '1,2,3,4,5,6,7'
list_words = number_word.split(',')
print(list_words) # ['1', '2', '3', '4', '5', '6', '7']

Copy by Value V.S Copy by Reference

2022-06-22_000351.jpg

2022-06-22_000705.jpg