Python learning list, for loop, slice, tuple

Posted by Michael on Fri, 11 Feb 2022 21:32:54 +0100

Python learning (2)

list

The list consists of a series of elements arranged in a specific order. The list can store almost all elements such as letters, numbers and strings. There is no relationship between the elements. The list is somewhat similar to a one-dimensional array.

In Python, lists are represented by square brackets [] and elements are separated by commas. Specific examples are given below:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones)			# ['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']

However, we usually can't directly use the elements in the list for this output. Next, we mainly learn a series of operations on the list.

Access list elements

A list is an ordered collection. If you want to access the elements in the list, just tell the Python interpreter the index of the elements in the list, that is, point out the name of the list, point out the index of the elements, and put it in square brackets.

It should be noted that the index of the list starts from 0. Therefore, to access any element of the list, you only need to subtract its position by one and take the result as the index.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones[1])			#Huawei

From the above, we can see that the output result no longer contains square brackets and quotation marks. At this time, we can directly operate the output result as follows:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones[4].upper())			#OPPO

It can be seen that lowercase oppo is converted to uppercase oppo.

In particular, Python provides a special syntax for the last list element. By setting the index value to - 1, Python can return the value of the last element. Similarly, based on this, we can decrement the index and use the index value - 2 to return the value of the penultimate element.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones[-1])				#vivo
print(mobilephones[-2])				#oppo
print(mobilephones[4])				#oppo

As you can see from the above, index value - 2 and index value 4 return the same result.

Therefore, when using the index to call the elements in the list, we can either add 1 from 0 from left to right to use the index, or subtract one from - 1 from right to left to use the index.

Modify list elements

If you want to modify an element in the list, first specify the list name and the index of the element to be modified, and then replace the original value with the new value.

#The following list of mobliephones can be used to convert Apple to Apple

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
mobilephones[0] = "Apple"
print(mobilephones)				#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']

It can be seen from the print results that Apple has been successfully replaced by apple. This method can be used to modify the values of other elements in the list.

Insert element in list

Insert element at the end of the list

The append() method is usually used to add elements to the end of the list, as follows:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
mobilephones.append("One plus")
mobilephones.append("ZTE")
print(mobilephones)			#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo', 'Yijia', 'ZTE']

Insert element in list

Using the insert() method, you can add a new element anywhere in the list. To do this, you need to set the index and value of the new element.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
mobilephones.insert(2,"ZTE")
print(mobilesphones)		#['Apple', 'Huawei', 'ZTE', 'Samsung', 'Xiaomi', 'oppo', 'vivo']

As shown above, the new value is successfully inserted into the element with index value of 2. Similarly, the element with index value of 2 and its subsequent elements move one bit to the right.

Delete list element

Delete elements using del statements

If you know the specific position of the element to be deleted in the list, you can use the del statement:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones)			#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']
del mobilephones[2]
print(mobilephones)			#['Apple', 'Huawei', 'Xiaomi', 'oppo', 'vivo']

You can see that Samsung with index 2 has been successfully deleted from the list.

It should be noted that del is a statement, not a method, so there are no parentheses when using it.

Delete elements using pop()

After using del statement to delete an element from the list, we can't continue to use the value of the element, but sometimes we want to delete the value of an element and use the element once after deletion. At this time, we can use pop() method.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones)					#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']
last_element = mobilephones.pop()
print(last_element)					#vivo
print(mobilephones)					#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo']

From the above, we can see that the last element after using pop is no longer in the list. At the same time, we can use the deleted element for new operations.

You can also delete an element anywhere in the list by using the pop() method. You only need to specify the index of the element to be deleted in parentheses.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones)					#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']
del_element = mobilephones.pop(3)
print(del_element)					#millet
print(mobilephones)					#['Apple', 'Huawei', 'Samsung', 'oppo', 'vivo']

It can be seen that Xiaomi with an index value of 3 has been successfully deleted, and we can use the deleted elements at the same time.

Delete element based on value

If we only know the value of the element to be deleted and do not know the specific location of the element to be deleted, we can use the remove() method to delete the element in the list.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
del_element = "Huawei"
mobilephones.remove(del_element)
print(mobilephones)							#'Apple', 'Povo', 'Apple','povo ','povo','povo '

It can be seen that the element "Huawei" has been successfully deleted. At the same time, it should be noted that the subordinate code is:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
del_element = mobilephones.remove("Huawei")
print(del_element)			#none
print(mobilephones)			#['Apple', 'Samsung', 'Xiaomi', 'oppo', 'vivo']

It can be seen that since we know what value is deleted from the beginning, we can use this value directly. If you remove this element, you cannot assign the value of the removed element to other variables. As shown in the second and third lines above, the output result is none.

Sort the list

Generally, the sorting of elements in the list is unpredictable, but when operating on the list, we often want the elements in the list to be in order. Therefore, Python provides the sort() method and the sorted() function to sort the list.

# The sort() method permanently changes the order of the elements in the list

name = ["yuntianhe","hanlingsha","murongziying","liumengli"]
name.sort()
print(name)		#['hanlingsha', 'liumengli', 'murongziying', 'yuntianhe']

#We can also sort alphabetically, just pass the reverse parameter to the sort() method and make the value of the parameter equal to True

name = ["yuntianhe","hanlingsha","murongziying","liumengli"]
name.sort(reverse = True)
print(name)		#['yuntianhe', 'murongziying', 'liumengli', 'hanlingsha']

#The sorted() function can display elements in a specific order without breaking their original order in the list

name = ["yuntianhe","hanlingsha","murongziying","liumengli"]
print(sorted(name))		#['hanlingsha', 'liumengli', 'murongziying', 'yuntianhe']
print(name)				#['yuntianhe', 'hanlingsha', 'murongziying', 'liumengli']

#You can also pass the parameter reverse = True to the function sorted() to sort in alphabetical order.

Differences between methods and functions:

In most cases, the method needs a specific object to call, and the function needs to pass in the object to be processed.

Print list in reverse order

If you want to reverse the order of the elements in the list, you can use the reverse() method.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
mobilephones.reverse()
print(mobilephones)			#['vivo', 'oppo', 'Xiaomi', 'Samsung', 'Huawei', 'Apple']

#If you want to return to the original order, you can use the reverse method on the list again.

Gets the length of the list

The length of the list can be obtained quickly by using the function len(). Python calculates the length of the list from 1.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
len = len(mobilephones)
print(len)			#6

List index error

If you want to get the fifth element for a list of four elements, the following error occurs:

name = ["yuntianhe","hanlingsha","murongziying","liumengli"]
print(name[4])

'''
IndexError: list index out of range
 Indicates that this is an index error. The entered index value exceeds the range of the list.
'''

for loop

Basic format of for loop

The for loop in Python is different from that in other languages. The for loop in Python is mainly used to traverse each value in the object in order. For the for loop in Python, there is no need to set the step value. It will automatically loop until all the elements in the processed object are read. An example of a for loop is given below:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
for mobilephone in mobilephones:
    print(mobilephone)				#Statement 1
    print(1)						#Statement 2

#	Apple 1 	 Huawei 1 	 Samsung 1 	 Xiaomi 1 	 oppo1 	 vivo1

'''
for Execution process of loop;
First from the list mobilephones Read the value of the first element and store it in the variable mobilephone Next, the part of the loop body is executed, where Python The part of the loop body in the loop is not represented by curly braces, but by indentation. The statements continuously indented by one unit under the loop belong to the part of the loop body and will be executed in turn. As shown above, statement 1 and statement 2 belong to the same loop body. After the value of the first element is executed, the value of the second element in the list is saved to mobilephone , and then execute until the last element of the list is processed.
'''

Perform the operation at the end of the cycle

In the previous part, we mentioned that the statements that continuously indent one unit after the loop are part of the loop body. Therefore, if you want to perform some operations after the loop, you only need to put the code behind the for loop without indenting.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
for mobilephone in mobilephones:
    print(mobilephone)				#Statement 1
print("There are many brands of mobile phones")				#Statement 2
'''
Apple
 Huawei
 Samsung
 millet
oppo
vivo
 There are many brands of mobile phones
'''

You can see that statement 1 is executed six times, while statement 2 is executed only once.

Common errors in the for loop

Forget indent

Be sure to indent the lines of code that are part of the loop after the for loop statement.

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
for mobilephone in mobilephones:
print(mobilephone)
'''
print(mobilephone)	
   ^
IndentationError: expected an indented block
 As mentioned above, the system will prompt you for indentation errors, and the expected indented code block is not found.
'''

Similar to the unwanted indentation after the lower loop, if__ Forget to indent the extra lines of code in the loop body, It often does not cause Python to report errors, but only causes logical errors in the output of statements. When this problem occurs, you should carefully check the indentation between codes to solve it.

Unnecessarily indented

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
	print(mobilephones)
    
'''
print(mobilephones)
    ^
IndentationError: unexpected indent
 It can be seen that the second line of the prompt is unnecessarily indented
'''

#If unnecessary indentation is made after the cycle, the following occurs:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
for mobilephone in mobilephones:
    print(mobilephone)
    print("There are many brands of mobile phones")
    
'''
Apple
 There are many brands of mobile phones
 Huawei
 There are many brands of mobile phones
 Samsung
 Many brands of mobile phones
 millet
 There are many brands of mobile phones
oppo
 There are many brands of mobile phones
vivo
 There are many brands of mobile phones

For this problem, the compiler will not report an error, but it does not conform to the logic of the output. Therefore, when this problem occurs, you need to carefully check the indentation value of the code.
'''

Missing colon

The colon at the end of the for statement is to tell Python that the next line is the first line of the loop. If the colon is omitted, the following error will occur:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
for mobilephone in mobilephones
    print(mobilephone)
    
'''
for mobilephone in mobilephones
                              ^
SyntaxError: invalid syntax
 This will prompt syntax errors. We need to check carefully to solve this problem.
'''

List of values

Use the range() function to generate a series of numbers

The range() function in Python can generate a series of consecutive numbers:

for value in range(1,5):
    print(value)
'''
1
2
3
4
'''

It can be seen that the number generated by the range() function starts from the first specified number and ends with the last specified number - 1.

When using the range() function to create a list, you can also specify the step value as follows:

for value in range(1,5,2):
    print(value)
'''
1
3
'''

As can be seen from the above, we have created a numerical value starting from 1 and stepping into 2 until reaching 4.

Converts the number generated by the range() function to a list of numbers

You can use the list() function to convert the result of range() directly into a list

numbers = list(range(1,5))
print(numbers)					#[1, 2, 3, 4]

Simple statistics on the list of numbers

Using the max(),min(),sum() function, you can easily get the maximum, minimum and sum of the number list.

numbers = list(range(1,5))
print(max(numbers))				#4
print(min(numbers))				#1
print(sum(numbers))				#10

List parsing

List parsing refers to merging the for loop and the code for creating new elements into one line, and automatically attaching new elements:

numbers = [number**2 for number in range(1,5)]
print(numbers)				#[1, 4, 9, 16]

#The above code creates a value of 1-4, calculates the square of the value, and puts the calculated result in the list, which is equivalent to the code below

numbers = []
for number in range(1,5):
    numbers.append(number**2)
print(numbers)					#[1, 4, 9, 16]

It can be seen that list parsing can reduce the number of relevant code lines. To use list parsing, first specify a list name, such as numbers, then specify an open parenthesis, and define an expression to generate the value to be stored. Then write a for loop to provide the value to the expression, and finally add the right parenthesis.

section

Slicing refers to getting some elements in the list. To create a slice, you need to specify the index of the first element and the last element to be used. When it is the same as the range() function, the slice stops before reaching the specified second index. The second to third elements of the list are extracted as follows:

mobilephones = ["Apple","Huawei","Samsung","millet","oppo","vivo"]
print(mobilephones[1:3])			#['Huawei', 'Samsung']

When slicing, you can also use the form of negative index mentioned earlier:

mobilephones = ["Apple", "Huawei", "Samsung", "millet", "oppo", "vivo"]
print(mobilephones[-3:-1])			#['Xiaomi', 'oppo']

It can be seen that we extracted the 4th to 5th elements by using negative index.

At the same time, positive index and negative index can be mixed, but it is necessary to ensure that the small index value comes first. If no start index is specified, Python will extract from the beginning. If no end index is specified, Python will extract until the end of the list.

Traversal slice

If you want to traverse the elements in the slice, you can use the for loop to traverse the slice:

mobilephones = ["Apple", "Huawei", "Samsung", "millet", "oppo", "vivo"]
for mobile in mobilephones[1:5]:
    print(mobile)

'''
Huawei
 Samsung
 millet
oppo
'''

Copy list

To copy the list, you can create a new slice including the whole list by omitting the start index and end index at the same time. As can be seen below, there are two lists at this time.

mobilephones = ["Apple", "Huawei", "Samsung", "millet", "oppo", "vivo"]
new_mobilephones = mobilephones[:]
print(new_mobilephones)			#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']
new_mobilephones.append("Meizu")
print(mobilephones)				#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']
print(new_mobilephones)			#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo', 'Meizu']

It should be noted that if we want to create a new list, we cannot assign a list to another list directly, but should create it in the form of slices. As follows:

mobilephones = ["Apple", "Huawei", "Samsung", "millet", "oppo", "vivo"]
new_mobilephones = mobilephones
print(new_mobilephones)			#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo']
new_mobilephones.append("Meizu")
print(mobilephones)				#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo', 'Meizu']
print(new_mobilephones)			#['Apple', 'Huawei', 'Samsung', 'Xiaomi', 'oppo', 'vivo', 'Meizu']

From the above comparison, it can be seen that if the list is created by assignment, essentially no new list is generated, but the original list is shared with the new list. At this time, there is actually only one list.

tuple

Tuples are similar to lists, but are represented by parentheses. Like lists, tuples use indexes to access elements. The characteristic of tuple is that the elements in tuple cannot be modified.

#As follows, a tuple is defined
numbers = (100,20)
#The elements in the tuple can be obtained through the index value. The format of the index value is the same as that of the list
print(numbers[0])					#100
print(numbers[1])					#20

#If you try to modify the value of a tuple, the following error occurs
numbers[0] = 20

'''
    numbers[0] = 20
TypeError: 'tuple' object does not support item assignment
 It is suggested that the data of tuple type does not support modification
'''

Traverse all values of tuples

Like lists, tuples use a for loop to traverse all elements:

numbers = (100,20)
for number in numbers:
    print(number)
'''
100
20
'''

Modify tuple variable

Although the value in the tuple variable cannot be modified, the tuple variable can be re assigned. If you want to modify the value in the numbers tuple, you can redefine:

numbers = (100,20)
print(numbers)				#(100, 20)

numbers = (500,100)
print(numbers)				#(500, 100)

Topics: Python list