立即学习:https://edu.csdn.net/course/play/26676/338778?utm_source=blogtoedu
列表是可修改的对象
可改变
>>> lst = [1,2,3,4]
>>> lst[2]=300
>>> lst
[1, 2, 300, 4]
不可直接增加
>>> lst[4]=999
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
可以通过调用lst中其他元素进行增减改变
>>> dir(lst)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> help(lst.append)
Help on built-in function append:
append(object, /) method of builtins.list instance
Append object to the end of the list.
>>> lst.append("python")
>>> lst
[1, 2, 300, 4, 'python']
当执行此方法后,无返回值
>>> lst.append("python")
>>> lst
[1, 2, 300, 4, 'python']
>>> id(lst)
1984455196288
>>> lst.append("lesson")
>>> lst
[1, 2, 300, 4, 'python', 'lesson']
>>> id(lst)
1984455196288
元素增加,但内容不会发生改变
所属id相同,返回值为none
列表作为容器,其地址不会改变
插入insert()
>>> lst.insert(0,10)
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson']
在第一个元素前插入10
函数extend
>>> help(lst.extend)
Help on built-in function extend:
extend(iterable, /) method of builtins.list instance
iterable为可迭代对象(列表,字符串....)用可迭代对象的元素扩展列表
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson']
>>> lst2 = ["a","b"]
>>> lst.extend(lst2)
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson', 'a', 'b']
>>> lst2
['a', 'b']
>>> lst.extend("book")
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson', 'a', 'b', 'b', 'o', 'o', 'k']
删除列表中元素
>>> help(lst.pop)
Help on built-in function pop:
pop(index=-1, /) method of builtins.list instance
Remove and return item at index (default last).
remove(value, /) method of builtins.list instance
Remove first occurrence of value.
>>> lst.pop()
'k'
>>> lst
[10, 1, 2, 300, 4, 'python', 'lesson', 'a', 'b', 'b', 'o', 'o']
>>> lst.pop(0)
10
>>> lst
[1, 2, 300, 4, 'python', 'lesson', 'a', 'b', 'b', 'o', 'o']
#指定删除某个位置的元素,并将列表返回
Raises ValueError if the value is not present.
remove 删除指定元素
>>> lst.remove("b")
>>> lst
[1, 2, 300, 4, 'python', 'lesson', 'a', 'b', 'o', 'o']
>>>