Python 列表 元組 基礎操作

2021-09-10 17:26:44 字數 976 閱讀 7849

列表與元組都是元素的線性集合,都是序列,不同的是,列表中的元素是可變的,而元組中的元素是不可變的。列表使用表示,而元組使用()表示。

another =[1

,2,3

,4,5

]# 增加元素

# 在末尾新增元素6)

# 在指定索引位置新增元素,在索引為0的位置新增元素10

another.insert(1,

10)# 刪除元素 按照元素內容刪除

another.remove(3)

# 修改元素 也即列表的可變性

another[0]

=10# 檢視元素 序列的索引分片都適用

another[0:

3]# 查詢元素索引 第乙個與要查詢的元素的值相同的索引值

another.index(10)

# 列表排序

another.sort(

)# 清空列表

another.clear(

)

another =(1

,2,3

,4,5

)temp_tuple =(8

,9)# 元組可以直接使用 + 來進行合併

new_tuple = another + temp_tuple

# 元組不支援刪除單個元素,可以使用del刪除整個元組

del another

# 元組也不支援修改元素

# 將會產生異常 typeerror: 'tuple' object does not support item assignment

another[0]

=10# 元組訪問可以使用索引和分片

another[0]

another[1:

3]

雖然元組中的元素無法修改,但是如果說元組中的某一項元素時列表或者其他的可變元素,則還是可以發生改變的。但是元素列表這個指向是不會發生改變的。

列表,元組,基礎操作

a,列表的定義及格式 定義 列表是乙個可修改的,元素以逗號為分割,以中框號包圍的有序序列 格式 變數名 元素1,元素2,naems c羅 劉能 梅西 print naems print type naems b,列表的序列操作 我們能夠對列表進行相加 重複 索引 切片,迴圈遍歷等操作 lst1 1,...

Python列表元組操作

names 申屠康豔 徐盼 施穎蕾 周鼎翔 周聖峰 周韓偉 周彥斌 周祥德 周帥育 周群璨 往列表新增元素 names.extend 周帥泉 周鵬飛 胡雪珍 在列表結尾新增多個元素,就是在列表中新增另乙個列表 names.insert 2,徐愉繁 在第三個位置新增元素 從列表中刪除元素 names....

Python基礎 列表和元組

判斷列表中是否含有某元素 if element in list orif element not in list dir dir list add class contains delattr delitem delslice doc eq format ge getattribute getite...