[Python] Ch1: Python Basics - 03 List

List 串列

List 用來儲存一連串有順序的資料,如:

countries = ['Taiwan', 'Janpan', 'America']
print(countries)
['Taiwan', 'Janpan', 'America']

取得 List 裡有幾個元素: len()

length = len(countries)
length
[Out]: 3

取得List 裡的元素

list_name[index]
countries[0]
[Out]: 'Taiwan'

取得最後一個元素

list[-1]
print(countries[-1])
[Out]: America
list.index(x[, start[, end]])

範圍取值: list slicing

list[start_index:end_index:sep]
countries[0:1]
[Out]: ['Taiwan']
countries[::3]
[Out]: ['Taiwan']

增加 List 裡面的元素

append method

list.append(object)

將一個新的元素加到 list 的尾端。

countries.append('Korea')
countries
['Taiwan', 'Janpan', 'America', 'Korea']

insert method

list.insert(position, object)

將一個新的元素加到指定的 list 位置。

countries.insert(-1, 'China')
countries
['Taiwan', 'Janpan', 'America', 'China', 'Korea']

extend method

list_1 = [object1, object2, object3, ...]
list_2 = [object0]
list_2.extend(list_1)
countries_2 = ['Malaysia', 'Singapore']
countries.extend(countries_2)
countries
['Taiwan', 'Janpan', 'America', 'China', 'Korea', 'Malaysia', 'Singapore']

移除 List 裡的元素

remove method

list.remove(object)
countries.remove('China')
countries
['Taiwan', 'Janpan', 'America', 'Korea', 'Malaysia', 'Singapore']

pop method

list.pop(index)

如果括號內不指定index, 預設是最後一個元素(-1)

countries.pop()
countries
['Taiwan', 'Janpan', 'America', 'Korea', 'Malaysia']

List 與 for-loop

for item in list:
    print(item)
for country in countries:
    print(country, end=', ')
Taiwan, Janpan, America, Korea, Malaysia,

用 for-loop 來建立 List

temp = []
for i in range(10):
    temp.append(i ** 2)
temp
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

pyhonic

a = [x ** 2 for x in range(10)]
a
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
c = [x ** 2 for x in b]
c
[1, 4, 9, 16, 25, 36, 49, 64, 81]