Operation on a list
-
You can think of analogous properties of arrays
- example of list in Python:
code:
list=['a','b','c','d']
print(list)
results:
['a', 'b', 'c', 'd']
3.1.1Accessing list elements
code:
list=['a','b','c','d'] print(list[0])
results:
a
PS:You can manipulate elements in a list by manipulating strings.
3.1.2Index from 0 to the end not 1
code:
list=['a','b','c','d'] print(list[0]) print(list[1])
results:
a
b
3.1.3Use the individual values in the list
code:
message="The first letter of the alphabet is"+" "+list[0] print(message)
results:
The first letter of the alphabet is a.
3.2 Modify,add and delete elements
The list we have made is already static .
3.2.1Modify the elements
code:
list=['a','b','c','d'] list[0]='A' print(list)
results:
['A', 'b', 'c', 'd']
3.2.2Add elements tothe list
(1)Add the elements at the end of list
code:
list=['a','b','c','d'] list.append('e') print(list)
results:
['a', 'b', 'c', 'd', 'e']
PS:We can use the"append()" to fill a empty list
code:
list=[] list.append('a') list.append('b') list.append('c') list.append('d') print(list)
results:
['a', 'b', 'c', 'd']
(2)Insert the elements into the litst
code:
list.insert(2,'z') print(list)
results:
['a', 'b', 'z', 'c', 'd']
3.2.3Delete the elements from the list
(1)Use "del()" to delete elements
code:
del list[2] print(list)
results:
['a', 'b', 'c', 'd']
(2)Use pop() to delete elements
PS:pop(弹出,stack) Pop the end of the elements in list .
code:
popped_list=list.pop() print(list) print(popped_list)
results:
['a', 'b', 'c']
d
PS:The different of the del and pop is that if you want to use the elements and pop it ,please use "pop".If you only want to delete them, please use the del to delete elements.
(3)The element anywhere in the pop-up list
code:
temp=list.pop(2) print(list) print(temp)
results:
['a', 'b']
c
(4)Deletes elements by value
code:
print(list) list.remove('e') print(list)
results:
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd']