Python - tuple的使用

Python的tuple使用

👉tuple與list的最大不同是list的內容在宣告後可以修改,tuple則不行。
如果tuple在執行階段修改則會出現錯誤訊息。

👉宣告時元素用"[ ]" 型態為list。
     如果用 "( )"時型態則為 tuple。

# tupleclassmates = ('Michel', 'Bob', 'John')
print(classmates)
宣告一個型態tuple的變數classmates。

[執行結果]
('Michel', 'Bob', 'John')



👉 tuple與listu,也可混合搭配使用:
classmates = ('Michel', 'Bob', 'John', ['newclassmate1', 'newclassmate2'])
宣告一個含有list的tuple資料型態

classmates[3][0] = 'Wesley'classmates[3][1] = 'Peter'print(classmates)
這時候tuple裡的list元素可以被改變。

[執行結果]
('Michel', 'Bob', 'John', ['Wesley', 'Peter'])


[完整內容]
# tupleclassmates = ('Michel', 'Bob', 'John')
print(classmates)

classmates = ('Michel', 'Bob', 'John', ['newclassmate1', 'newclassmate2'])
classmates[3][0] = 'Wesley'classmates[3][1] = 'Peter'print(classmates)



留言

這個網誌中的熱門文章

1/35 TIGER I(虎式坦克)