"Python programming from introduction to practice" -- list operation

Posted by leeroy1 on Tue, 01 Feb 2022 19:14:19 +0100

  the creation and simple operations of the list are described earlier, but some of the operations described above can not meet all the test scenarios. For example, we need to perform the same operation on the whole list. The method described earlier is inefficient and the amount of code is relatively large. Here we focus on some efficient list processing.

Traversal list

  in fact, how to traverse the list is easy to implement in python. We can implement the operation through the for loop. Specific examples are as follows:

# input
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
for bicycle in bicycles:
    print(bicycle)

# output
trek
cannondale
redline
specialized

  if there is an increase or decrease of elements in the list in the program, we can also use the for loop to traverse the whole list. In this way, it doesn't matter the length of the list. In addition, when writing a for loop, you can specify any name for the temporary variable used to store each value in the list. In the example, the variable bicycle is a temporary variable. You also need to follow the rules of variable naming mentioned earlier. During the execution of circular statements, we can still operate on the elements in the list to meet the requirements of the program. For example, in the process of output, the initial capital is required:

# input
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
for bicycle in bicycles:
    print(bicycle.title())

# output
Trek
Cannondale
Redline
Specialized

Indentation

  in Python language, the relationship between the code line and the previous code line is judged according to the indentation. It can be understood through the following two examples:

# Example 1
# input
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
for bicycle in bicycles:
    print(bicycle)
    print("This is my bicycle" +" " + bicycle.title())

# output
trek
This is my bicycle Trek
cannondale
This is my bicycle Cannondale
redline
This is my bicycle Redline
specialized
This is my bicycle Specialized
# Example 2
# input
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
for bicycle in bicycles:
    print(bicycle)
print("These are my bicycles")

# output
trek
cannondale
redline
specialized
These are my bicycles

  you can clearly see the difference between the two examples. In example 1, the second print function will be executed once in each cycle. Because it has the same indentation relationship with the first print, the program thinks that the second print function is still in the cycle. In example 2, the second print function maintains the same indentation relationship as the for statement, so the program thinks that the second print function is not a statement in the loop. Therefore, the second print function is executed after the loop is executed.

List of values

  the elements in the list can be strings, characters, numbers and other elements. For a list composed of pure numbers, it belongs to a numerical list. In data visualization, almost all data are processed by a set of numbers (such as temperature, distance, population, longitude and latitude, etc.). Lists are also very suitable for storing digital collections, and Python provides many tools to help you deal with digital lists efficiently.

1. The function range() can quickly generate a series of numbers

# input
for number in range(1,6):
    print(number)

# output
1
2
3
4
5

   it needs to be explained here that the range of numbers generated by the function range(x,y) is [x, y-1]. For the introduction and use of the range() function, you can find more detailed use methods in the compiler through help(range).

2. The function list() can quickly convert a string of numbers into a list

# input
number = list(range(1,6))
print(number)

# output
[1, 2, 3, 4, 5]

3. List analysis

   list parsing allows you to generate the list in the above example with only one line of code. List parsing is to combine the for loop and the code for creating new elements into one line, and automatically attach new elements. The specific syntax is as follows:

# input
numbers = [value for value in range(1,6)]
print(numbers)

# output
[1, 2, 3, 4, 5]

   let's start by introducing the composition of this grammar. First, specify a descriptive list name, such as numbers; Then, specify an open square bracket,
And define an expression to generate the value you want to store in the list. In this example, the expression is value, and no other more complex operations are defined here; Next, write a for loop to provide a value to the expression, plus the right square brackets. In this example, the for loop is for value in range(1,6), which supplies values 1 to 5 to the expression value. Note that there is no colon at the end of the for statement here. In this way, you can create a list in one line of code.

section

  the last article introduced how to access a single element of the list. In fact, we can also deal with some elements of the list - what Python calls slicing. To create a slice, specify the index of the first and last element to use. For example:

# input
numbers = [value for value in range(1,30,2)]
print(numbers)
print(numbers[0:5])
print(numbers[:5])
print(numbers[10:])
print(numbers[-5:])
print(numbers[-5:-3])


# output
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
[21, 23, 25, 27, 29]
[21, 23, 25, 27, 29]
[21, 23]

  if you do not specify the first index, Python will start indexing from the beginning of the list by default. If you want the slice to end at the end of the list, you can use a similar syntax. As mentioned in the previous article, negative indexes return elements at a corresponding distance from the end of the list, so you can output any slice at the end of the list.

  when you get a slice, it is essentially a list. In other words, we can also migrate the list operation to slice.

# input
numbers = [value for value in range(1,30,2)]
for number in numbers[0:5]:
    print(number)


# output
1
3
5
7
9

Copy list

  to copy a list, create a slice that contains the entire list by omitting both the start index and the end index ([:]). This allows Python to create a slice that starts with the first element and ends with the last element, copying the entire list. Please see the following two examples:

# Example 1
# input
numbers = [value for value in range(1,30,2)]
values = numbers[:]
numbers.append(30)
values.append(31)
print(numbers)
print(values)


# output
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 30]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31]
# Example 2
# input
numbers = [value for value in range(1,30,2)]
values = numbers
numbers.append(30)
values.append(31)
print(numbers)
print(values)


# output
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 30, 31]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 30, 31]

  the two here can tell us that if you want to copy the whole list, you can't simply create a new list name, and then copy the name of the list to the new list. This kind of processing will only make the two lists become the same list, but the names are different. If you operate on any list, the same operation will be synchronized to another list. This is the opposite of what you want two separate lists, so you should abandon the practice in example 2. These two examples also tell us that the copy list should follow the way of slicing.

tuple

  lists are ideal for storing data sets that may change during program operation. The list is modifiable, which is critical to dealing with changing elements. However, sometimes you need to create a series of immutable elements, and tuples can meet this requirement. Python calls values that cannot be modified immutable, while immutable lists are called tuples. Tuples look like lists, but are identified by parentheses rather than square brackets. Once a tuple is defined, its elements can be accessed using an index, just like a list element.

# Error example
# input
exmple = (range(0,200,50))
exmple[0] = 10
print(exmple[0])


# output
Traceback (most recent call last):
  File "C:/script/Tuple.py", line 5, in <module>
    exmple[0] = 10
TypeError: 'range' object does not support item assignment

  how to traverse the whole element of tuple, you can also use the for loop to realize the traversal function. Although the elements of tuples are not modifiable, we can modify tuples by changing the variables of the whole tuple.

# input
exmple = (range(0,200,50))
for value in exmple:
    print(value)

exmple = (range(0,200,60))
for value in exmple:
    print(value)


# output
0
50
100
150

0
60
120
180

Topics: Python