A list,
Data types: numeric types, strings, lists, dictionaries, primitives, sets, iterators, generators, functions
1. What is a list?
Equivalent to arrays in other languages.
Lists are container data types provided by Python. Mutable and ordered.
Mutable – The value of each element in the list is variable, the length of the list is variable, and the order in the list is variable. (Support to add, delete, change)
Order – Each element can be positioned by subscript
2. List literals
Enclosed by [], there are multiple elements, each separated by a comma.
Such as:
# The elements of the list are separated by commas
[1.2.3]
Elements in Python lists can be of any type supported by Python
# And different elements in the same list can have different types
[10.'abc'.True]
Any type of data can be used as a list element
a = 10
list1 = [a, 132.'abc'.True.10.23[1.2] and {'a':10}]
# an empty list
[]
Copy the code
3. Get the list element
The syntax is the same as for strings to get characters
A, get a single element
List [subscript]Get the element in the list corresponding to the specified subscript
Copy the code
Ex. :
list1 = [1.2.3.4]
print(list1[0]) # 1
print(list1[-1]) # 4
Copy the code
B. Obtain some elements (slice)
The result of a string is a new string, and the result of a list is a list.
Grammar:
List [start subscript: End subscript: step size]Copy the code
Example:
list1 = ['a'.'b'.'c'.'d'.'e']
print(list1[1:3])
print(list1[-3:3])
print(list1[:2])
print(list1[::-1])
Copy the code
C, Fetch all elements one by one (traversal)
Method 1: You can use the for loop to directly traverse the list to get each element.
When you manipulate elements it doesn’t have to do with subscripts.
list1 = ['a'.'b'.'c'.'d'.'e']
for item in list1:
print(item)
Copy the code
Method 2: Iterate over list elements by iterating over their subscripts.
When you manipulate elements with respect to subscripts you do it this way.
list1 = ['a'.'b'.'c'.'d'.'e']
for index in range(len(list1)):
print(list1[index])
Copy the code
Two, add, delete and change
1. Add (add list element)
A, append
Adds the specified element at the end of the specified list.
List.append (element)Copy the code
Ex. :
list1 = [1.2.3.4.5]
list1.append(6)
print(list1) # [1, 2, 3, 4, 5, 6]
Copy the code
B, the insert
Inserts the specified element before the specified subscript.
List. Insert (subscript, element)Copy the code
Ex. :
list1 = [1.2.3.4.5]
list1.insert(3.3.5)
print(list1) # [1, 2, 3, 3.5, 4, 5]
Copy the code
2, delete
A, del
Deletes the element with the specified subscript. Del is the keyword and can delete anything.
Delete the entire list without subscripting.
Note: An error is reported if the subscript is out of bounds.
delList [subscript]delThe list ofCopy the code
Ex. :
list1 = [1.2.3.4.5]
del list1[0]
print(list1) # [2, 3, 4, 5]
Copy the code
Note: both additions and deletions are changes to the original list, and subscripts are reassigned.
B, remove
Delete not by subscript, but by element. If there is no element, the program will report an error.
List. Remove (element)Copy the code
Case 1:
list1 = [1.2.3.4.5]
list1.remove(5)
print(list1) # [1, 2, 3, 4]
Copy the code
Example 2:
list1 = [1.2.5.4.5]
list1.remove(5)
print(list1) # [1, 2, 4, 5]
Copy the code
Note: if there are duplicate elements, remove only the first one from left to right.
C, pop
In contrast to del and remove, pop deletes with a return value (the element that was deleted is returned); Del and remove return no value
List. pop() list. pop(subscript)Copy the code
With no arguments, POP fetches the last element of the list from the list;
With subscripts, POP fetches the element corresponding to the specified subscript from the list.
list1 = [1.2.3.4.5.5]
num1 = list1.pop()
print(num1)
print(list1)
Copy the code
Two pits encountered while deleting elements
-
Pit 1: Traversal with elements
Problems encountered: traversing the list to delete part of the elements, delete not all!
Error in subscript traversal
age_list = [14.9.33.44]
for index in range(len(age_list)):
age = age_list[index]
if age < 18:
age_list.pop(index)
print(age_list)
Copy the code
# Solution: Cut edges to copy the original list while traversing
Create a new list to store the age, to ensure that the subscript changes when deleting
# Iterate over unchanged elements
Use remove to remove the element
age_list = [1.2.33.44]
temp = age_list[:]
for age in temp:
if age < 18:
age_list.remove(age)
print(age_list)
Copy the code
-
Pit 2: subscript traversal
Problems: Incomplete deletion, and will cross the line.
The following code does not implement the function
for index in range(len(age_list)):
age = age_list[index]
if age < 18:
age_list.pop(index)
print(age_list)
Copy the code
# use the while loop to control the number of loops.
age_list = [14.9.33.44]
index = 0
new_ages = []
while index < len(age_list):
age = age_list[index]
if age < 18:
del_item = age_list.pop(index)
new_ages.append(del_item)
else:
index += 1
print(age_list, new_ages)
Copy the code
3, change
List [subscript] = new valueCopy the code
Modifies the value of the specified subscript in the list
list1 = [1.2.3]
list1[0] = 'abc'
print(list1) # ['abc', 2, 3]
Copy the code
Example: There is a list of students’ scores, those requiring less than 60 points change to “see you next class”, and count the number of students.
count = 0
scores = [11.22.33.66.77.88]
for index in range(len(scores)):
if scores[index] < 60:
count += 1
scores[index] = 'See you in the next class'
print('There are %d people in the next class'%count)
print(scores)
Copy the code
Third, the correlation operation of the list
1. Correlation operation:
A, support +, * operation
The list of1+ list2
Copy the code
Combining elements from two lists produces a new list.
print([1.2.3] + ['a'.'b'.'c'])
# [1, 2, 3, 'a', 'b', 'c']
Copy the code
List * NCopy the code
Repeat the elements in the list N times to produce a new list
B. Support comparison operation
Comparing uppercase is similar to the string comparison size.
list1 = [1.2.3]
list2 = [1.2.3]
print(list1 == list2) # True
print(list1 == [1.3.2]) # False
Copy the code
2, in and not in
The elementinThe list ofCopy the code
Checks whether the specified element exists in the list
print([1.2] in [1.2.3]) # False
Copy the code
3, len
len(list)Copy the code
Gets the number of elements in the list.
print(len([[1.2].2.'a'.'agc'])) # 4
Copy the code
4, the list
Only sequences can be converted to lists, and all sequences can be converted to lists
list(data)Copy the code
When you convert, you convert all the elements in the sequence to the elements in the list
list1 = list('hello')
print(list1) # ['h', 'e', 'l', 'l', 'o']
list2 = list(range(10.20))
print(list2) # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Copy the code
Note: It is not possible to use the name of a type that Python provides for us, otherwise it would be dangerous.
5. Sequence other methods
max(sequence)Get the element with the largest value in the sequence
min(sequence)Get the element with the smallest value in the sequence
sum(sequence)Find the sum of all elements in the sequence
Copy the code
Note: The above three methods require that the elements in the sequence be of the same type, and that the type supports operation and addition. (Generally used for numeric sequences)
print(max([1.2.3.3.5.5.9]))
print(min([1.2.3.3.5.5.9]))
print(sum(range(101))) Calculate the sum from 1 to 100
Copy the code