This article will introduce one of the most commonly used sequence types in Python: lists
1. Create a list
The literal of a list is [], and its corresponding built-in function is list(), both of which can be used to create lists
>>> Use a literal to create an empty list
>>> li = []
>>> Create an empty list using built-in functions
>>> li = list(a)>>> Use built-in functions to convert other sequence types to list types
>>> li = list((1.2.3))
Copy the code
Lists can hold various types of elements, from basic types such as int and float to standard types such as dict and STR
>>> li = [27.3.7, {'Python': 'Beautiful'}, 'Hello', (0.2),0.3]]
>>> type(li)
# <class 'list'>
Copy the code
2. Add elements
append()
: Adds a single element to the end of the listextend()
: Extends a new list to the end of the original listinsert()
: Inserts a single element into the specified position in the list
>>> li = ['one'] # li: ['one']
>>> li.append('two') # li: ['one', 'two']
>>> li.extend(['three'.'five']) # li: ['one', 'two', 'three', 'five']
>>> li.insert(3.'four') # li: ['one', 'two', 'three', 'four', 'five']
Copy the code
3. Delete elements
pop()
: Deletes and returns the last element in the list. You can also specify the index of the element to be deleted by specifying the parameterremove()
: Deletes the first element that matches the parameter value without returning the contentclear()
: Clears the entire list without returning the contents
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> lastVal = li.pop() # li: ['one', 'two', 'three', 'four']
>>> firstVal = li.pop(0) # li: ['two', 'three', 'four']
>>> li.remove('three') # li: ['two', 'four']
>>> li.clear() # li: []
Copy the code
4. List index
An index allows you to access and modify elements at a specified location
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> Access the element at the specified location
>>> li[0]
# 'one'
>>> # modify the element at the specified position
>>> li[0] = 'new'
>>> Access the element at the specified location
>>> li[0]
# 'new'
Copy the code
5. List slices
(1) Basic use
In addition to the ability to access individual elements through indexes, slices can be used to access elements in a specified range
Simply put, slicing specifies a range using two indexes, called the start index and the end index
The range of slices includes the elements specified by the start index, but not the elements specified by the end index. It is a half-closed and half-open interval
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> li[1:3]
# ['two', 'three']
Copy the code
(2) Default index
If the start index is not specified, the default value is 0. When the end index is not specified, the default is the list length
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> li[:4] # start index not specified. Default is 0
# ['one', 'two', 'three', 'four']
>>> li[1:] # End index not specified, defaults to list length
# ['two', 'three', 'four', 'five']
Copy the code
When both the front and back indexes are omitted, a copy of the original list is created
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> li[:]
# ['one', 'two', 'three', 'four', 'five']
Copy the code
Note here that slicing is a copy of the original list, and slicing does not affect the original list
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> li_slice = li[:]
>>> li_slice.append('six')
>>> li_slice
# ['one', 'two', 'three', 'four', 'five', 'six']
>>> li
# ['one', 'two', 'three', 'four', 'five']
Copy the code
(3) Negative index
In addition to positive integer indexes, negative integer indexes can be counted from back to front
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> li[-1]
# 'five'
>>> li[1: -1]
# ['two', 'three', 'four']
Copy the code
(4) Set the step size
All of the above operations operate on consecutive elements in the list, is there a way to allow us to skip the selection of elements
The answer is yes, and the third parameter in the slicing operation is used to specify the step size. Otherwise, the default is 1
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> li[::2]
# ['one', 'three', 'five']
Copy the code
With step size Settings, we can easily do some interesting things, such as reversing lists
>>> li = ['one'.'two'.'three'.'four'.'five']
>>> li[::-1]
# ['five', 'four', 'three', 'two', 'one']
Copy the code
6. List operators
List operators allow arithmetic operators that are used for primitive data types to be applied to lists, but their meanings may vary
(1) Join operator (+) : join two lists
>>> ['one'.'two'] + [ 'three'.'four']
# ['one', 'two', 'three', 'four']
Copy the code
(2) Repeat operator (*) : to repeat the list of elements specified times
>>> ['one'.'two'] * 2
# ['one', 'two', 'one', 'two']
Copy the code
With the repeat operator, we can easily initialize a list of the same elements
>>> [0] * 10
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Copy the code
(3) Membership operators (in, not in) : determine whether a value belongs to the list
>>> 'one' in ['one'.'two']
# True
Copy the code
7. List method
(1) count() : counts the number of times the specified value appears in the list
>>> li = [1.5.9.3.5.7.2.5.8]
>>> li.count(5)
# 3
Copy the code
(2) index() : finds the index where the specified value first appears in the list
>>> li = [1.5.9.3.5.7.2.5.8]
>>> li.index(5)
# 1
Copy the code
(3) Reverse () : Arranges the elements in the list in reverse order (operating on the original list without returning values)
>>> li = [1.2.3.4.5]
>>> li.reverse()
>>> li
# [5, 4, 3, 2, 1]
Copy the code
(4) sort() : sort the list (operating on the original list, no return value)
>>> li = [1.5.2.4.3]
>>> li.sort()
>>> li
# [1, 2, 3, 4, 5]
Copy the code
The sort() method does not return any values. If you want to return a sorted list, you can use the sorted() method
In fact, the sorted() method can be applied to any sequence, but always returns a list
>>> li = [1.5.2.4.3]
>>> sorted_li = sorted(li)
>>> sorted_li
# [1, 2, 3, 4, 5]
Copy the code
The sort() method can also accept two optional arguments, key and reverse
key
You can specify a sort target, which is typically used when the list elements are complex objects
>>> li = [{
'fruit': 'apple'.'price': 123
}, {
'fruit': 'banana'.'price': 321
}, {
'fruit': 'orange'.'price': 213
}]
>>> li.sort(key = lambda item: item['price'])
>>> li
# [{'fruit': 'apple', 'price': 123}, {'fruit': 'orange', 'price': 213}, {'fruit': 'banana', 'price': 321}]
Copy the code
reverse
Is a Boolean parameter. Default isFalse
, indicates the order, if isTrue
Is in reverse order
>>> li = [1.5.2.4.3]
>>> li.sort(reverse = True)
>>> li
# [5, 4, 3, 2, 1]
Copy the code
8. Advanced skills
(1) List iteration
- Iterate over the values of elements in the list
>>> li = ['A'.'B'.'C']
>>> for item in li: print(item)
# A
# B
# C
Copy the code
- Iterate over both index and element values in the list
>>> li = ['A'.'B'.'C']
>>> for index, value in enumerate(li): print(index, value)
# 0 A
# 1 B
# 2 C
Copy the code
- Iterate over both lists at the same time
>>> name = ['Alice'.'Bob'.'Cathy']
>>> grade = [85.98.95]
>>> for i, j in zip(name, grade): print(i, j)
# Alice 85
# Bob 98
# Cathy 95
Copy the code
(2) List derivation
List comprehensions provide an easy way to create lists in the following basic format:
new_list = [expression(i) for i in old_list if condition(i)]
Copy the code
Translate into general statement:
new_list = []
for i in old_list:
if condition(i):
new_list.append(expression(i))
Copy the code
① Handling elements: for example, exponentiating each element
>>> old_list = list(range(10))
>>> new_list = [i**2 for i in old_list]
>>> new_list
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Copy the code
② Filter elements: for example, filter odd elements
>>> old_list = list(range(10))
>>> new_list = [i for i in old_list if i % 2= =0]
>>> new_list
# [0, 2, 4, 6, 8]
Copy the code
(3) Matrix transpose: To solve this problem is more complicated, we need to use nested list derivation
The nested format of the list derivation is as follows:
new_list = [expression(i, j) for i in old_list_one for j in old_list_two]
Copy the code
Translate into general statement:
new_list = []
for i in old_list_one:
for j in old_list_two:
new_list.append(expression(i, j))
Copy the code
Nested format variations of list comprehensions are as follows:
new_list = [[expression(i, j) for i in old_list_one] for j in old_list_two]
Copy the code
Translate into general statement:
new_list = []
for i in old_list_one:
temp = []
for j in old_list_two:
temp.append(expression(i, j))
new_list.append(temp)
Copy the code
Solve the matrix transpose:
>>> old = [[1.2.3], [4.5.6], [7.8.9]]
>>> new = [[row[i] for row in old] for i in range(len(old))]
>>> new
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Copy the code
9, yuan group
Having said so much, I finally finished the list part of the knowledge point, and then I will briefly supplement the related knowledge point of tuples
Tuples are similar to lists in that they differ mainly in the following ways:
- Lists are essentially mutable and tuples are immutable (you can’t directly modify the contents of a tuple element), which is the biggest difference between them
- Use is consistent with lists except for creation methods and operations that directly modify the contents of a tuple element
Since the method of creating tuples is relatively special, the following describes the method of creating tuples and some points to note
As opposed to a list, the tuple literal is () and its built-in function is tuple(), which can be created either way
>>> Create an empty tuple using a literal
>>> tup = ()
>>> Create an empty tuple using the built-in function
>>> tup = tuple(a)>>> Use built-in functions to convert other sequence types to tuple types
>>> tup = tuple([1.2.3])
Copy the code
However, unlike what you might expect, creating a tuple with one element does not use the following syntax
>>> tup = (1)
>>> type(tup)
# <class 'int'>
Copy the code
In fact, the literal tuple is (), which is somewhat inaccurate
This syntax cannot be used when creating tuples with one element, and it is possible to create tuples with multiple elements without using ()
>>> tup = 1.>>> type(tup)
# <class 'tuple'>
>>> tup = 1.2.3
>>> type(tup)
# <class 'tuple'>
Copy the code