列表跟元组一样,都是序列,但元组是不可变的,列表是可变的,它们可以被修改。因此,列表不仅可以做元组能做的事情,而且还能做元组所不能做的事情。
创建列表
和元组的区别就是,用来包装元素的是方括号而不是圆括号。
#创建一个带有一些元素的列表,然后用for循环显示出来 inventory=["sword","armor","shield","healing potion"] print("Your items:") for item in inventory: print(item)
inventory=["sword","armor","shield","healing potion"] #获取列表长度 print("You have",len(inventory),"items in your possession.") #利用in测试成员关系 if "healing potion" in inventory: print("in inventory") #对列表进行索引 print("inventory[1]",inventory[1]) #对列表进行切片 print("inventory[1:3]",inventory[1:3])输出:
对列表进行连接
列表只能连接相同类型的序列(不过,貌似,字符串和数字可以混)
#连接两个列表 inventory=["sword","armor","shield","healing potion"] chest=["gold","gems"] inventory+=chest print(inventory)输出:
#连接两个列表 inventory=["sword","armor","shield","healing potion"] chest=[1,2] inventory+=chest print(inventory)输出:
列表和元组的最大区别就是,列表是可变的,元组是不可变的。
通过索引对列表元素进行赋值
inventory=["sword","armor","shield","healing potion"] inventory[0]="crossbow" print(inventory)输出:
注意:虽然可以利用索引机制为列表中已有的元素赋新值,但是不能用这种方式创建新元素。对不存在的元素的赋值操作都会引发一个错误。
inventory=["sword","armor","shield","healing potion"] inventory[4]="4" print(inventory)输出:
inventory=["sword","armor","shield","healing potion"] inventory[2:4]="crossbow" print(inventory)输出:
inventory=["sword","armor","shield","healing potion"] inventory[2:4]=["crossbow"] print(inventory)输出:
注意:赋值的时候,应该用列表进行赋值。上边把crossbow当成了一个列表,列表元素为"c","r","o","s","s","b","o","w"
删除列表元素
可以用del删除列表中的元素-只需在del后面指明待删除的元素即可。删除元素之后并不会在序列中产生一个空位。列表的长度会减一,被删除元素后面的所有元素都会“往前走”一个位置。
inventory=["sword","armor","shield","healing potion"] del inventory[1] print(inventory)输出:
inventory=["sword","armor","shield","healing potion"] del inventory[0:2] print(inventory)输出: