[Python 1-7] Python hand in hand tutorial — detailed list

Time:2021-6-15

list

Author: Vlad
Source Vlad (official account: fulade_ me)

Lists, in other languages, are also called listsarrayIs a series of elements arranged in a specific order. You can create lists that contain all the letters in the alphabet, the numbers 0-9, or the names of all family members. You can also create several lists and put them in one list.
In Python, use square brackets[]To represent a list, and separate the elements with commas. Here is a simple example of a list of several common fruits:

fruits = ['Apple','Banana','Pear','Orange']
print(fruits)
['Apple','Banana','Pear','Orange']

<!–more–>

Access list data

A list is an ordered set of data, and each element has a positional parameter. Like the one abovefruitsIn the list, whereAppleThe location parameter of is0BananaThe location parameter is1. To access a list element, indicate the name of the list, then the index of the element, and place it in square brackets.
For example, the following code from the listfruitsChoose the first fruit from the list:

fruits = ['Apple','Banana','Pear','Orange']
print(fruits[0])
Apple

The index starts at 0

All list position parameters are from0The beginning is not from 1, for beginners, this must be remembered. If you find that the elements extracted in the coding process are different from what you expect, please see if you have made such a simple mistake.
The index of the second list element is 1. According to this simple way of counting, to access any element of the list, you can subtract its position1And index the results. For example, to access the fourth list element, use the index3
The following code accesses the index1and3Fruit in the garden:

fruits = ['Apple','Banana','Pear','Orange']
print(fruits[1])
print(fruits[3])
Banana
Orange

Python provides a special syntax for accessing the last list element. By specifying the index as-1To let Python return the last list element:

fruits = ['Apple','Banana','Pear','Orange']
print(fruits[-1])
Orange

Here’s the returnOrange. This syntax is useful because you often need to access the last element without knowing the length of the list.
This Convention also applies to other negative indexes, such as index-2Returns the penultimate list element, index-3Returns the penultimate list element, and so on.

Modify list elements

To modify a list element, specify the name of the list and the index of the element to be modified, and then specify the new value of the element.
For example, suppose you have a list of fruits in which the first element isAppleHow to modify its value?

fruits = ['Apple','Banana','Pear','Orange']
print(fruits[0])
print(fruits)
Apple
['Apple','Banana','Pear','Orange']

#Start by changing the first element to cherry
fruits[0] = 'Cherry'
print(fruits[0])
print(fruits)
Cherry
['Cherry','Banana','Pear','Orange']

Add elements to the list

You may want to add new elements to the list for many reasons. For example, a new kind of fruit has been added to the market, which needs to be stored in the marketfruitsThere’s a new kind of fruit in it. Python provides many ways to add new data to existing lists.
1. Add elements at the end of the list
When you add a new element to a list, the easiest way is to attach the element to the end of the list.

fruits = ['Apple','Banana','Pear','Orange']
print(fruits)
fruits.append('Cherry')
print(fruits)

methodappend()Put the elementCherryAdded to the end of the list without affecting all other elements in the list.

['Apple','Banana','Pear','Orange']
['Apple','Banana','Pear','Orange','Cherry']

append()It can meet our needs of creating arrays dynamically. For example, we can first create an empty list and use a series ofappend()Statement to dynamically add elements.
For example:

fruits = []
fruits.append('Apple')
fruits.append('Banana')
fruits.append('Pear')
print(fruits)
['Apple','Banana','Pear']

This kind of creation is common, because many times, we only know which elements need to be added to the list and which elements do not need to be added during the execution of the code.
2. Insert elements in the list

usage methodinsert()You can add new elements anywhere in the list. However, you need to specify the index and value of the new element.

fruits = ['Apple','Banana','Pear']
fruits.insert(0,'Orange')
print(fruits)
['Orange','Apple','Banana','Pear']

In this example,OrangeWas inserted into the index for0It’s the right place. This moves each of the other elements in the list one position to the right.
It should be noted that the index of the inserted data cannot exceed the current maximum index value of the listfruits.insert(10,'Orange')It’s a mistake. You can have a try.

Remove element from list

We often need to remove an element from the list, for example, if there is aAppleThis kind of fruit needs to be taken off the shelves because it is out of stock. We need to take it off the shelvesAppleRemove from the list. You can delete elements from the list by location or value.
1. Delete elements with del statement
If you know the position of the element to be deleted in the list, you can use thedelsentence.

fruits = ['Apple','Banana','Pear']
print(fruits)
['Apple','Banana','Pear']
del fruits[0]
print(fruits)
['Banana','Pear']

usedelA list element at any location can be deleted if its index is known. The following example shows how to deletefruitsThe second element in the list

fruits = ['Apple','Banana','Pear']
print(fruits)
['Apple','Banana','Pear']
del fruits[1]
print(fruits)
['Apple','Pear']

From the output, the second element has been removed.
2. Use pop() to delete elements
Sometimes you want to remove an element from the list and then use its value. For example, if you take a certain fruit off the shelf, you need to put it into tomorrow’s purchasing list.
methodpop()Remove the element at the end of the list and allow you to use it again.

fruits = ['Apple','Banana','Pear']
print(fruits)
poped_fruit = fruits.pop()
print(fruits)
['Apple', 'Banana']
print(poped_fruit)
Pear

implementpop()Method, the last element of the original array is removed and the last element is returned as a return value.
3. Elements anywhere in the pop list
You must have guessed that we just need topop()Method to import the index of the element you want to remove.

fruits = ['Apple','Banana','Pear']
print(fruits)
['Apple', 'Banana', 'Pear']
first_fruit = fruits.pop(0)
print(first_fruit)
Apple

Don’t forget that every time you use pop (), the element that pops up is no longer in the list.
If you’re not sure whether to use the Del statement or thepop()Method, here is a simple criterion: if you want to remove an element from the list and no longer use it in any way, usedelStatement. If you want to continue to use the element after deleting it, use the methodpop()
4. Delete the element according to the value
Sometimes we don’t know where the value to be removed from the list is. If you only know the value of the element to be deleted, useremove()method.

fruits = ['Apple','Banana','Pear']
print(fruits)
['Apple', 'Banana', 'Pear']
fruits.remove('Apple')
print(fruits)
['Banana', 'Pear']

methodremove()Only the first specified value that appears in the list is deleted. In other words, ifApplestayfruitsList appears more than once, callremove()Method, only the first one is deletedApple

fruits = ['Apple','Banana','Pear','Apple']
print(fruits)
['Apple', 'Banana', 'Pear','Apple']
fruits.remove('Apple')
print(fruits)
['Banana', 'Pear','Apple']

Consolidated list

In the lists we create, the order of elements is often unpredictable. Because we don’t always control the order in which users provide data. We often need to present information in a specific order. Sometimes you want to keep the original order of the list elements, and sometimes you need to adjust the order. Python provides many ways to organize lists, which can be selected according to the specific situation.

Use the method sort() to sort the list permanently

Python methodsort()It makes it easy for you to sort the list. Let’s say you have a list of fruits and have them arranged in alphabetical order. To simplify this task, we assume that all values in the list are lowercase.

fruits = ['pear','banana','apple']
print(fruits)
['pear', 'banana', 'apple']
fruits.sort()
print(fruits)
['apple', 'banana', 'pear']

methodsort()The permutation order of list elements is permanently modified. Now?fruitsThey are arranged in alphabetical order and can no longer be restored to the original order.
We can also arrange the list elements in reverse alphabetical order by simply addingsort()Method passing parametersreverse=TrueThat’s it.

fruits.sort(reverse=True)
print(fruits)
['pear', 'banana', 'apple']

Use the function sorted() to sort the list temporarily

To preserve the original order of list elements and present them in a specific order, use the functionsorted(). functionsorted()Allows you to display list elements in a specific order without affecting their original order in the list. Let’s try tofruitsList to call this function.

fruits = ['pear','banana','apple']
print(fruits)
['pear', 'banana', 'apple']
print(sorted(fruits))
['apple', 'banana', 'pear']
#Output fruits again
print(fruits)
['pear', 'banana', 'apple']

Notice that the function is calledsorted()After that, the order of the elements in the list does not change. If you want to display the list in reverse alphabetical order, you can also add thesorted()Transfer parametersreverse=True
When not all the values are lowercase, it is more complicated to arrange the list in alphabetical order. We will answer this question in detail later.

Reverse order output list

To reverse the order of list elements, use thereverse(). hypothesisfruistThe list is arranged by purchase time, and the fruits can be easily arranged in reverse order:

fruits = ['pear','banana','apple']
print(fruits)
['pear', 'banana', 'apple']
fruits.reverse()
print(fruits)
['apple', 'banana', 'pear']

reverse()It doesn’t mean that the list elements are arranged in the reverse order of alphabet, it’s justreversalThe order in which the list elements are arranged.
methodreverse()The permutation order of the list elements can be changed permanently, but it can be restored to the original permutation order at any time. For this reason, you only need to call reverse () on the list again

The length of the list

Using functionslen()You can quickly learn the length of the list


fruits = ['pear','banana','apple']
len(fruits)
3

Getting the length of the list is very useful in the development process. For example, we uselen()How many kinds of fruits are currently on sale can be obtained with one method.

Try it yourself

7-1 store the names of some friends in a list and name them names. Access each element in the list in turn to print out the name of each friend.
7-2 guest list: if you could invite anyone (living or dead) to dinner, who would you invite? Please create a list of at least 3 people you want to invite, and then print the list.
7-3 modify the guest list: you just learned that one of the guests was unable to attend the appointment, so you need to invite another guest. Modify the guest list and replace the name of the guest who can’t attend the appointment with the name of the new guest.
Then print the list again.
7-4 add guests: you just found a bigger table to accommodate more guests. Please think about three more guests you would like to invite.
Use insert() to add a new guest to the beginning of the list.
Use insert() to add another new guest to the middle of the list.
Use append() to add the last new guest to the end of the list.
7-5 shortlist: you just learned that the new table can’t be delivered in time, so you can only invite two guests. Use pop() to delete guests from the list until there are only two guests. Every time a guest pops up from the list, print it.
7-7 look around the world: think of at least five places you’re eager to visit. Store these places in a list and make sure the elements are not in alphabetical order. Print the list in the original order. Don’t worry about the neatness of the output, just print the original Python list.
Use sorted () to print the list alphabetically without modifying it. Print the list again and verify that the order is the same.
Use sorted () to print the list in reverse alphabetical order without modifying it. Print the list again and verify that the order is the same.
Use reverse () to change the order of the list elements. Print the list and verify that the order has changed.
Use reverse () to change the order of the list elements again. Print the list and verify that the original order has been restored.
Use sort() to modify the list so that its elements are in alphabetical order. Print the list and verify that the order has changed.
Use sort() to modify the list so that its elements are arranged in reverse alphabetical order. Print the list and verify that the order has changed.

If you want to check the answers to your homework, you can goMy githu warehouse


[Python 1-7] Python hand in hand tutorial -- detailed list