1. Definition
A list is an ordered collection of objects, surrounded by square brackets [ ], and separated by commas
Lists are dynamic , elements can be added or removed at any time
Lists are heterogeneous and can contain data of different types
Duplicate elements are allowed in the list
Two, create
- Created by square brackets
- Created by the constructor list()
- Created via list comprehension
# 中括号创建
li1 = []
print(li1) # 输出:[]
li1 = [1, "2", True]
print(li1) # 输出:[1, "2", True]
# 构造方法list()创建
li2 = list()
print(li2) # 输出:[]
li2 = list("good") # 字符串、元组、列表、集合、字典等均可
print(li2) # 输出:['g', 'o', 'o', 'd']
# 列表推导式创建
li3 = [i for i in range(0,4)]
print(li3) # 输出:[0, 1, 2, 3]
3. List use
1. Index
Because the list is ordered, you can get the value of the corresponding position in the list through the index.
- Forward indexing, numbering starts from 0.
- Reverse index, numbering starts from -1.
Writing method: list[index]
li = [1, 2, 3, 4, 5]
print(li1[0]) # 输出:1
print(li1[-1]) # 输出:5
2. Slicing
Based on the index, instead of just taking a single value, you can take a section of the list.
Writing method: list[start: stop: step]
- start: Indicates the start index value, the default is 0
- stop: Indicates the end index value (not including the end index value itself), and takes the maximum index value by default.
- step: step value, the default is 1.
Note: Slicing follows the principle of closing first and opening later. The strat value starts from the start value itself, and stop takes the previous value of stop.
li = list("good boy")
print(li[0:-1:1]) # 输出:['g', 'o', 'o', 'd', ' ', 'b', 'o']
print(li[2:4]) # 输出:['o', 'd'],省略step
print(li[:4]) # 输出:['g', 'o', 'o', 'd'],省略start、step
print(li[2:]) # 输出:['o', 'd', ' ', 'b', 'o', 'y'],省略stop、step
print(li[::-2]) # 输出:['y', 'b', 'd', 'o'],省略start、stop,逆序、步进2打印。
3. Operator
Repeat: use the * operator to repeat the production list elements
Merge: Use the + operator to combine two lists into one
li1 = [1, 'a'] * 5
print(li1) # 输出:[1, 'a', 1, 'a', 1, 'a', 1, 'a', 1, 'a']
li2 = ["a", "b"]
li3 = list([1, 2, 3])
print(li3 + li2) # 输出:[1, 2, 3, 'a', 'b']
4. Member detection
in: Checks if an element is in the list. If it returns True, otherwise it returns False.
not in: Checks whether a list does not contain an element. Return True if not, otherwise return False.
li = [i for i in range(1,4)]
print(1 in li) # 输出:True
print(100 not in li) # 输出:True
4. Common methods
1、append()
Add a single object to the end of the list
Writing method: list.append(item)
Input parameter: object item
return: None
li = []
li.append("good")
li.append([1, "a"])
li.append({'a': 1})
print(li.append(1)) # 输出:None
print(li) # 输出:['good', [1, 'a'], {'a': 1}, 1]
print(len(li)) # 输出:4
2、extend()
Append all elements of an iterable to the end of the list
Writing: list.extend(iterable)
Input parameter: iterable object iterable
return: None
li = []
li.extend("good")
li.extend([1, "a"])
print(li.extend({'a': 1})) # 输出:None
print(li) # 输出:['g', 'o', 'o', 'd', 1, 'a', 'a']
print(len(li)) # 输出:7
3、insert()
Insert an object at the specified index position
Writing method: list.insert(index, item)
Input parameters: index value index, object item
return: None
The original index position and the following elements are shifted one bit backward
li = [1, 2, 3]
print(li.insert(0, "good")) # 输出:None
print(li) # 输出:['good', 1, 2, 3]
li.insert(3, ["a", "b"])
print(li) # 输出:['good', 1, 2, ['a', 'b'], 3]
4、pop()
removes and returns the element at the specified index
Writing: list.pop(index) or list.pop()
Input parameter: index value index, optional
Returns: the element at the specified index, or the end element if no index is specified
Raises IndexError if the index value is incorrect or the list is already empty
li = [1, 2, 3, 4, 5]
print(li.pop(1)) # 输出:2
print(li) # 输出:[1, 3, 4, 5]
print(li.pop()) # 输出:5
print(li) # 输出:[1, 3, 4]
li.pop(3) # IndexError: pop index out of range
li1 = []
li1.pop() # IndexError: pop from empty list
5、remove()
Removes the first element in the list equal to item
Writing method: list.remove(item)
Input parameter: specified element item
return: None
If the target element does not exist, ValueError is raised
li = [1, 2, "a", "b"]
print(li.remove(2)) # 输出:None
print(li) # 输出:[1, 'a', 'b']
li.remove("c")
print(li) # ValueError: list.remove(x): x not in list
6、sort()
Sort the list in-place, using only < for comparison between items
Writing method: list.sort(key=None, reverse=False)
Input parameter: supports 2 keyword parameters:
- key: Specifies a function with one argument to extract the comparison key from each list element
- reverse: The default value is False for ascending order, True for descending order
return: None
nums = [2, 4, 3, 1, 5]
print(nums.sort()) # 输出:None
print(nums) # 输出:[1, 2, 3, 4, 5]
nums.sort(reverse=True)
print(nums) # 输出:[5, 4, 3, 2, 1]
words = ["Python", "Java", "R", "Go"]
words.sort(key=len)
print(words) # 输出:['R', 'Go', 'Java', 'Python']
7、reverse()
Reverses the order of elements in a list
Writing method: list.reverse()
Entry parameters: none
return: None
The inversion is only for the index value, and the elements are not compared with each other
nums = [8, 1, 5, 85, 77]
print(nums.reverse()) # 输出:None
print(nums) # 输出:[77, 85, 5, 1, 8]
Five, list nesting
Nested list refers to storing lists inside lists
Common methods for lists all apply to nested lists
li = [['a', 'b', 'c'], [1, 2, 3]]
print(li[1][2]) # 输出:3
li[0].append('d')
print(li) # 输出:[['a', 'b', 'c', 'd'], [1, 2, 3]]
li[0][1] = 1
print(li) # 输出:[['a', 1, 'c', 'd'], [1, 2, 3]]
Six, list comprehension
List comprehension refers to the loop to create a list, which is equivalent to a simplified version of the for loop to create a list.
Writing: [x for x in ... if ...]
# for循环创建列表
li1 = []
for i in range(1, 11):
if i % 2 == 0:
li1.append(i ** 2)
print(li1) # 输出:[4, 16, 36, 64, 100]
# 列表推导式创建列表
li2 = [i ** 2 for i in range(1, 11) if i % 2 == 0]
print(li2) # 输出:[4, 16, 36, 64, 100]
# 无else时,if在for循环之后
# for循环创建列表
li1 = []
for i in range(1, 11):
if i % 2 == 0:
li1.append(i ** 2)
else:
li1.append(i)
print(li1) # 输出:[1, 4, 3, 16, 5, 36, 7, 64, 9, 100]
# 列表推导式创建列表
li2 = [i ** 2 if i % 2 == 0 else i for i in range(1, 11)]
print(li2) # 输出:[1, 4, 3, 16, 5, 36, 7, 64, 9, 100]
# 有else时,if…else在for循环之前