DAY 8
0

## Day -10 tuple與List

tuple 可放任意物件，但不可變 ;

tuple用法如下

• 建立多個元素
``````tupleSample = ("Groucho","Sam")
print(empty_tuple)

emptySample = "Sandy","Paul"
print(empty_tuple)

('Groucho', 'Sam')
('Sandy', 'Paul', 'Rose')
``````

``````vowels = ('a', 'e', 'i', 'o', 'i', 'u')
index = vowels.index('e')
print('The index of e:', index)
index = vowels.index('i')
print('The index of i:', index)

The index of e: 1
The index of i: 2
``````

``````print(type(vowels))
<class 'tuple'>
``````

``````marx_tuple = ( 'Groucho' , 'Chico' , 'Harpo')
a, b , c = marx_tuple

print(a)
print(b)
print(c)
``````

tuple 值直接對調(SWAP)，不用暫存變數

``````password = 'Hello' ,
icecream = 'Mary' ,

print(icecream)

('Mary',)
('Hello',)
``````

``````marx_list = ['Groucho' , 'Chico' , 'Harpo']
print(tuple(marx_list))
('Groucho', 'Chico', 'Harpo')

print(('Groucho' ,)+ ('Chico' , 'Harpo'))
('Groucho', 'Chico', 'Harpo')
``````

``````('yeah',) * 3
print(('yeah',) * 3)

('yeah', 'yeah', 'yeah')
``````

``````a = (7,2)
b = (7,2,9)
a == b
print(a == b)
``````

``````range_tuple = tuple(range(10))
print(type(range_tuple))
print(range_tuple)
print(range_tuple[:5:2])
(0, 2, 4)
``````

List 可放任意物件 ，可變。

List用法如下

• List 相加 有兩種方式，t1内存記憶體不同：
``````
t1 = ('one','two','three')
t2 = ('four')
print(id(t1))
print(t1 + t2)

t1 += t2
print(t1)
print(id(t1))

('one', 'two', 'three', 'four')
47210502568192
('one', 'two', 'three', 'four')
47210502433104

``````

tuple 與 串列 比較
tuple 通常可以取代List，但可操作的功能會少很多，且不能修改。
tuple優點:

• tuple 佔用的空間較少
• 不可能無意間修改tuple的項目和值
• tuple 可以當字典的key來使用

Python 基礎學習之旅12