python列表1_2

154 阅读1分钟

6、在列表中从左至右查找指定元素,找到了返回该值的下标/索引

index(查询元素, 起始位置, 结束位置) 查询元素参数必写, 不写默认全部,起始位置和结束位置就是从哪里开始找起。

如果index查找不到就报错

就相当于去酒店查房 多少号房

list1 = ['a', 1, True, 'b', 2, False, 3, 'hello', 'a']
# 0
print(list1.index('a'))
# 8
print(list1.index('a', 1))
# 找不到就报错: ValueError: 'c' is not in list
print(list1.index('c'))

7、列表中元素的增加

  • 往列表末尾追加一个元素

    append(元素)

list1 = ['a', 'b', 'c']
list1.append(True)
# ['a', 'b', 'c', True]
print(list1)
**规律:**列表的修改和增加都不需要重新赋值,直接改变原值,所以是可变类型

字符串,数字,布尔,复数都是一个值,改变需要重新赋值,都是不可变类型。
  • insert(索引, 元素) 往指定索引位置插入一个元素
list1 = ['a', 'b', 'c']
list1.insert(1, False)
# ['a', False, 'b', 'c']
print(list1)
  • extend() 往列表中添加多个元素 括号里放列表, 也是末尾追加
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list1.extend(list2)
# ['a', 'b', 'c', 1, 2, 3]
print(list1)