insert方法
insert() 函数用于将指定对象插入列表的指定位置。
语法 insert()方法语法: list.insert(index, obj)
参数 index -- 对象 obj 需要插入的索引位置。
obj -- 要插入列表中的对象。
返回值 该方法没有返回值,但会在列表指定位置插入对象。
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print(aList)
# 控制台
# [123, 'xyz', 'zara', 2009, 'abc']
extend方法
extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
语法 extend()方法语法: list.extend(seq)
参数 seq -- 元素列表,可以是列表、元组、集合、字典,若为字典,则仅会将键(key)作为元素依次添加至原列表的末尾。
返回值 该方法没有返回值,但会在已存在的列表中添加新的列表内容。
list1 = ['Google', 'Runoob', 'Taobao']
list2 = list(range(5))
# list2 扩展到list1里面
list1.append(list2)
print(list1)
print(list2)
print(list1)
# 列表
language = ['French', 'English', 'German']
# 元组
language_tuple = ('Spanish', 'Portuguese')
# 集合
language_set = {'Chinese', 'Japanese'}
# 添加元组元素到列表末尾
language.extend(language_tuple)
print('新列表: ', language)
# 添加集合元素到列表末尾
language.extend(language_set)
print('新列表: ', language)
#控制台
#['Google', 'Runoob', 'Taobao', [0, 1, 2, 3, 4]]
#[0, 1, 2, 3, 4]
#['Google', 'Runoob', 'Taobao', [0, 1, 2, 3, 4]]
#新列表: ['French', 'English', 'German', 'Spanish', 'Portuguese']
#新列表: ['French', 'English', 'German', 'Spanish', 'Portuguese', 'Chinese', 'Japanese']
count()方法
count() 方法用于统计某个元素在列表中出现的次数。
语法 count()方法语法: list.count(obj)
参数 obj -- 列表中统计的对象。
返回值 返回元素在列表中出现的次数。
aList = [123, 'xyz', 'zara', 'abc', 123]
print("Count for 123 : ", aList.count(123))
print("Count for zara : ", aList.count('zara'))
# 控制台
#Count for 123 : 2
#Count for zara : 1