Python list basic operations
Remember a word, called Gu head regardless of the tail
Let's start by defining a list
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]
Next, we'll do a series of operations on this list.
1. Slicing
Take the first and second of the values
Print (name[0],name[1]) results Jixuege Dajiba
Description
The above 0 and 1 refer to the small mark, from left to right in order from 0 onwards to 4
Print an interval
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]print (Name[:2]) print results [' jixuege ', ' Dajiba ']
Print the last one
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]print (Name[-1]) print results Youtianai
2. Append
For example, I want to add a person in.
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]name.append ("Xiha") print (name) results [' Jixuege ', ' Xitong ', ' Dajiba ', ' Youhua ', ' Boduoye ', ' cangjinkong ', ' Youtianai ', ' Xiha '
This will be appended to the end.
Another is inserting insert
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]name.insert (2, "Youhua") print (name) results [' Jixuege ', ' Dajiba ', ' Youhua ', ' Boduoye ', ' cangjinkong ', ' Youtianai ']
3. Modification
Direct modification can
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]name[2]= "wuming" Print (name) results [' Jixuege ', ' Dajiba ', ' wuming ', ' cangjinkong ', ' Youtianai ']
4. Delete
Direct emptying
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]name.clear () print (name) results []
Delete the specified element
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]name.remove ("Jixuege") print (name) results [' Dajiba ', ' Boduoye ', ' cangjinkong ', ' Youtianai ']
Delete the specified subscript
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]del name[2]print (name) print results [' jixuege ', ' Dajiba ', ' Cangjinkong ', ' Youtianai ']
Do not specify subscript to delete the last
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]name.pop () print (name) results [' Jixuege ', ' Dajiba ', ' Boduoye ', ' Cangjinkong ']
Specify subscript
name = ["Jixuege", "Dajiba", "Boduoye", "Cangjinkong", "Youtianai"]name.pop (1) print (name) results [' Jixuege ', ' Boduoye ', ' Cangjinkong ', ' Youtianai ']
Python List base operations