This article example describes the common operations of Python lists. Shared for your reference, as follows:
A list is an object consisting of a series of elements arranged in a particular order. Because lists usually contain more than one element, it is recommended that lists be given a name that indicates plurality.
We use square brackets ([]
) to represent a list, with commas separating the elements.
types=['Entertainment','Sports','Technology'] print(types)
Run results:
['Entertainment', 'Sports', 'Technology']
As you can see, printing the list prints out the square brackets as well.
1 Getting Elements
To get an element in the list, specify the index of the element in square brackets:
print('Third type:'+types[2])
Run results:
Third type: science and technology
When we request a list element, only the element itself is returned.
2 Indexing starts at 0
As in most programming languages, indexes are counted from zero. Therefore, if you need to get any element of the list, you can subtract its position by 1 for the index.
Specifying the index as -1 also allows you to get the last list element so that you can get the last element without knowing the length of the list:
print('The last one:'+types[-1])
Run results:
Last: Technology
This syntax also applies to other negative indexes. Index -2 gets the penultimate list element, index -3 gets the penultimate list element, and so on.
print('Penultimate:'+types[-2])
Run results:
Penultimate: Sports
3 New elements
- 3.1 End of list
append()
method can append elements to the end of the list:
('Finance and economics') print(types)
Run results:
['Entertainment', 'Sports', 'Technology', 'Finance']
append()
method is good for creating lists dynamically. We can create an empty list first, and then use a series ofappend()
method adds elements to the list.
colors=[] ('Green') ('Blue') ('Purple') print(colors)
Run results:
['green', 'blue', 'purple']
- 3.2 Designation of positions
insert()
A new element can be added at any position in the list. The inputs to this method are the index and value of the new element.
(0,'Red') print(colors)
Run results:
['Red', 'Green', 'Blue', 'Purple']
In this example, the value 'red' is inserted into the header of the list, and all existing elements in the list are shifted one position to the right.
4 Modifying elements
The syntax for modifying a list element is similar to the syntax for getting a list element. We can specify the list name, the index of the element to be modified, and the new value:
colors[0]='White' print(colors)
Run results:
['white', 'green', 'blue', 'purple']
5 Deleting elements
- 5.1
del()
If you know where in the list the element to be deleted is, then you can use del():
del colors[0] print(colors)
Run results:
['green', 'blue', 'purple']
- 5.2
pop()
Think of a list as a stack.pop()
method pops the top stack element (i.e., the last element at the end of the list) and returns that element.
print('Before implementation:'+str(colors)) poped_color=() print('Top stack element:'+poped_color) print('After implementation:'+str(colors))
Run results:
Before implementation: ['green', 'blue', 'purple']
Top-of-stack element: purple
Post-implementation: ['green', 'blue']
As long as the index of the element to be deleted is specified, thepop()
It can also be used to remove elements anywhere in the list:
print('Before implementation:'+str(colors)) poped_color=(0) print('Deleted elements:'+poped_color) print('After implementation:'+str(colors))
Run results:
Before implementation: ['green', 'blue']
Deleted element: green
Post-implementation: ['blue']
- 5.3 Comparison
del()
together withpop()
del()
: Removes an element from the list and does not use it again.pop()
: Removes an element from the list and needs to use it.
- 5.4 Deletion by value
remove()
print('Before implementation:'+str(colors)) ('Blue') print('After implementation:'+str(colors))
Run results:
Before implementation: ['blue']
After implementation: []
**Note:**remove()
Only the first specified value will be deleted. If you need to delete more than one value, you need to use a loop O(∩_∩)O~.
6 Sorting
- 6.1 Permanent ordering
sort()
types=['sport','travel','business'] () print("After sorting in positive alphabetical order:"+str(types)); (reverse=True) print("After sorting in reverse alphabetical order:"+str(types));
Run results:
After sorting in positive alphabetical order: ['business', 'sport', 'travel']
After sorting in reverse alphabetical order: ['travel', 'sport', 'business']
sort()
It permanently changes the order of the list elements (alphabetically). If you need to sort Chinese pinyin, you need to introduce a third-party library.
because ofsort()
Methods passing parametersreverse=True, it is then possible to arrange the elements according to the rule of reverse alphabetical order.
- 6.2 Provisional ordering
sorted()
function (math.)sorted()
It preserves the original ordering of the list elements and returns the sorted list.
types=['sport','travel','business'] print("Sorted:"+str(sorted(types))); print("Original list:"+str(types)); print("After sorting in reverse alphabetical order:"+str(sorted(types,reverse=True)));
Run results:
Sorted by: ['business', 'sport', 'travel']
Original list: ['sport', 'travel', 'business']
After sorting in reverse alphabetical order: ['travel', 'sport', 'business']
**Note:** After calling sorted(), the order of the elements of the original list is not changed, so it is called temporary sorting.
sorted()
The function also supports the parameterreverse=True, arranges the elements according to the rule of reverse alphabetical order.
- 6.3 Reverse order
reverse()
reverse()
Reverses the order of the original elements of the list.
types=['Entertainment','Sports','Technology'] print('Before Reverse Order:'+str(types)) () print(' After the reverse order: '+str(types))
Run results:
Pre-reverse order: ['Entertainment', 'Sports', 'Technology']
After reverse order: ['Technology', 'Sports', 'Entertainment']
7 List length len()
types=['Entertainment','Sports','Technology'] print(len(types))
Run results:
3
8 Indexing errors
When an indexing error occurs, it is recommended to print out the list or the length, which can help us to find out the cause of the error by looking at the content.
Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Python list (list) manipulation techniques summarized》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.