Introduction to Python self study list

Posted by blogfisher on Mon, 17 Jan 2022 19:42:40 +0100

Introduction to Python self-study (III) list

preface

Tip: you will learn all kinds of data that can be used in Python programs. You will also learn how to store data in variables and how to use these variables in programs.

1, What is the list

A list consists of a series of elements arranged in a specific order. You can create a list containing all the letters, numbers 0~9 or names of all family members in the alphabet; You can also add anything to the list, and there can be no relationship between the elements. Since lists usually contain multiple elements, it's a good idea to assign a plural name to the list (such as letters, digits, or names).

In Python, lists are represented by square brackets ([]) and elements are separated by commas. The following is a simple example of a list of bicycles:

bicycles.py

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles)

If you ask Python to print the list, python will print the internal representation of the list, including square brackets:

['trek', 'cannondale', 'redline', 'specialized']

Since this is not the output you want users to see, let's learn how to access list elements.

1.1 accessing list elements

Lists are ordered collections, so to access any element of a list, you just tell Python the location or index of that element. 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 extracts the first bike from the list bicycles:

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
❶ print(bicycles[0])

❶ illustrates the syntax for accessing list elements. When you request a list element, Python only returns the element, not square brackets and quotation marks:

trek

This is exactly what you want users to see - neat, clean output.

You can also call the string method described in Chapter 2 on any list element. For example, you can use the method title() to make the format of the element 'trek' Cleaner:

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles[0].title())

The output of this example is the same as the previous example, except that the initial T is capitalized.

1.2 index starts with 0 instead of 1

In Python, the index of the first list element is 0 instead of 1. This is true in most programming languages, which is related to the underlying implementation of list operations. If the result is unexpected, please see if you have made a simple one-to-one mistake. The index of the second list element is 1. According to this simple counting method, any element of the list can be accessed by subtracting its position by 1 and using the result as an index. For example, to access the fourth list element, use index 3.
The following code accesses bicycles at indexes 1 and 3:

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles[1])
print(bicycles[3])

These codes return the second and fourth elements in the list:

cannondale 
specialized

Python provides a special syntax for accessing the last list element. By specifying an index of - 1, python returns the last list element:

bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 
print(bicycles[-1])

These codes return 'specialized'. 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. For example, index - 2 returns the penultimate list element, index - 3 returns the penultimate list element, and so on.

1.3 use the values in the list

You can use the values in the list just like other variables. For example, you can use splicing to create messages based on the values in the list.
Let's try to extract the first bike from the list and use this value to create a message:

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
❶ message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)

We use the value of cycles [0] to generate a sentence and store it in the variable message (see ❶). The output is a simple sentence containing the first bike in the list:

My first bicycle was a Trek.

2, Modify, add, and delete elements

Most of the lists you create will be dynamic, which means that after the list is created, elements will be added or deleted as the program runs. For example, you create a game that requires players to shoot aliens from the sky; For this purpose, some aliens can be stored in the list at the beginning, and then deleted from the list every time an alien is shot, and added to the list every time a new alien appears on the screen. The length of the alien list will change throughout the game.

2.1 modifying list elements

The syntax for modifying list elements is similar to that for accessing list elements. To modify a list element, specify the list name and the index of the element to be modified, and then specify the new value of the element. For example, suppose there is a motorcycle list, the first element of which is' honda ', how to modify its value?
motorcycles.py

❶ motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
❷ motorcycles[0] = 'ducati' 
print(motorcycles)

We first define a motorcycle list, in which the first element is' honda '(see ❶). Next, we change the value of the first element to 'ducati' (see ❷). The output shows that the value of the first element has indeed changed, but the values of other list elements have not changed:

['honda', 'yamaha', 'suzuki'] 
['ducati', 'yamaha', 'suzuki']

You can change the value of any list element, not just the value of the first element.

2.2 adding elements to the list

You may want to add new elements to the list for many reasons. For example, you may want new aliens in the game, add visual data, or add new registered users to the website. Python provides a variety of ways to add new data to an existing list.

  1. Add an element at the end of the list
    When adding a new element to a list, the easiest way is to append the element to the end of the list. When you attach an element to a list, it is added to the end of the list. Continue to use the list in the previous example and add a new element 'ducati' at the end:
motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
❶ motorcycles.append('ducati') 
print(motorcycles)

The method append() adds the element 'ducati' to the end of the list (see ❶) without affecting all other elements in the list:

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']

The method append() makes it easy to create a list dynamically. For example, you can create an empty list and then add elements with a series of append() statements. Let's create an empty list and add the elements' honda ',' yamaha 'and' suzuki 'to it:

motorcycles = []
motorcycles.append('honda') 
motorcycles.append('yamaha') 
motorcycles.append('suzuki')
print(motorcycles)

The final list is exactly the same as that in the previous example:

['honda', 'yamaha', 'suzuki']

This way of creating lists is extremely common, because you often have to wait until the program runs before you know what data users want to store in the program. To control the user, you can first create an empty list to store the values that the user will enter, and then append each new value provided by the user to the list.

  1. Insert element in list
    Use the insert() method to add a new element anywhere in the list. To do this, you need to specify the index and value of the new element.
motorcycles = ['honda', 'yamaha', 'suzuki']
❶ motorcycles.insert(0, 'ducati') 
print(motorcycles)

In this example, the value 'ducati' is inserted at the beginning of the list (see ❶); The method insert() adds space at index 0 and stores the value 'ducati' there. This moves each existing element in the list one position to the right:

['ducati', 'honda', 'yamaha', 'suzuki']

2.3 removing elements from the list

You often need to delete one or more elements from the list. For example, after a player shoots an alien in the air, you are likely to delete it from the list of surviving aliens; When a user logs off his account in the Web application you create, you need to delete the user from the list of active users. You can delete the elements in the list according to the position or value.

  1. Delete elements using del statements
    If you know the position of the element to be deleted in the list, you can use the del statement.
motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
❶ del motorcycles[0] 
print(motorcycles)

The code at ❶ uses del to delete the first element in the list motorcycles - 'honda':

['honda', 'yamaha', 'suzuki'] 
['yamaha', 'suzuki']

Use del to delete a list element anywhere if its index is known. The following example demonstrates how to delete the second element in the previous list, 'yamaha':

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
del motorcycles[1] 
print(motorcycles)

The following output indicates that the second motorcycle has been removed from the list:

	['honda', 'yamaha', 'suzuki'] 
	['honda', 'suzuki']

In both examples, you can no longer access the value after it is removed from the list using the del statement.

  1. Delete the element using the method pop()
    Sometimes you delete an element from the list and then use its value. For example, you may need to obtain the x and y coordinates of the alien just shot to display the explosion effect in the corresponding position; In a Web application, you may want to remove users from the active member list and add them to the inactive member list.
    The method pop() deletes the element at the end of the list and allows you to use it later. The term pop comes from the analogy that a list is like a stack, and deleting the element at the end of the list is equivalent to popping the element at the top of the stack. Below, a motorcycle pops up from the list of motorcycles:
❶ motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
❷ popped_motorcycle = motorcycles.pop() 
❸ print(motorcycles)
❹ print(popped_motorcycle)

We first defined and printed the list motorcycles (see ❶). Next, we pop up a value from this list and store it in the variable popped_ In the motor cycle (see ❷). We then print the list to verify that a value has been deleted from it (see ❸). Finally, we print the pop-up value to prove that we can still access the deleted value (see ❹).

The output shows that the value 'suzuki' at the end of the list has been deleted and is now stored in the variable popped_ In motorcycle:

['honda', 'yamaha', 'suzuki'] 
['honda', 'yamaha']
suzuki

How does the method pop () work? Assuming that the motorcycles in the list are stored according to the purchase time, you can use the method pop() to print a message indicating which motorcycle was last purchased:

motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")

The output is a simple sentence indicating which motorcycle was recently purchased:

The last motorcycle I owned was a Suzuki.
  1. Pop up an element anywhere in the list
    In fact, you can use pop() to delete an element anywhere in the list by specifying the index of the element to be deleted in parentheses.
motorcycles = ['honda', 'yamaha', 'suzuki']
❶ first_owned = motorcycles.pop(0)
❷ print('The first motorcycle I owned was a ' + first_owned.title() + '.')

First, we pop up the first motorcycle in the list (see ❶), and then print a message about the motorcycle (see ❶). The output is a simple sentence describing the first motorcycle I bought:

 The first motorcycle I owned was a Honda.

Don't forget that whenever you use pop(), the pop-up element is no longer in the list.
If you are not sure whether to use del statement or pop() method, here is a simple criterion: if you want to delete an element from the list and don't use it in any way, use del statement; If you want to continue using the element after it is deleted, use the method pop().

  1. Delete elements based on values sometimes you don't know where the value you want to delete from the list is. If you only know the value of the element to be deleted, you can use the method remove(). For example, suppose we want to delete the value 'ducati' from the list of motorcycles.
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
print(motorcycles)
❶ motorcycles.remove('ducati') 
print(motorcycles)

The code at ❶ lets Python determine where 'ducati' appears in the list and delete the element:

['honda', 'yamaha', 'suzuki', 'ducati'] 
['honda', 'yamaha', 'suzuki']

When you use remove() to remove an element from the list, you can then use its value. Delete the value 'ducati' below and print a message indicating the reason for deleting it from the list:

❶ motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
print(motorcycles)
❷ too_expensive = 'ducati'
❸ motorcycles.remove(too_expensive)
print(motorcycles)
❹ print("\nA " + too_expensive.title() + " is too expensive for me.")

After defining the list at ❶, we store the value 'ducati' in the variable too_ In expense (see ❷). Next, we use this variable to tell Python which value to remove from the list (see ❸). Finally, the value 'ducati' has been removed from the list, but it is also stored in the variable too_ In expense (see ❹), we can print a message indicating the reason for deleting 'ducati' from the list of motorcycles:

['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
A Ducati is too expensive for me.

3, Organization list

In the list you create, the order of elements is often unpredictable, because you don't always control the order in which users provide data. Although this is inevitable in most cases, you 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 specific situations.

3.1 permanently sort the list using the method sort()

The Python method sort() allows you to sort the list more easily. Suppose you have a list of cars in alphabetical order. To simplify this task, we assume that all values in the list are lowercase.
cars.py

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
❶ cars.sort()
print(cars)

The method sort() (see ❶) permanently modifies the order of the list elements. Now, cars are arranged in alphabetical order and can no longer be restored to the original order:

['audi', 'bmw', 'subaru', 'toyota']

You can also arrange the list elements in reverse alphabetical order by simply passing the parameter reverse=True to the sort() method. The following example arranges the list of cars in reverse alphabetical order:

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
cars.sort(reverse=True)
print(cars)

Similarly, changes to the order of list elements are permanent:

['toyota', 'subaru', 'bmw', 'audi']

3.2 use the function sorted() to temporarily sort the list

To preserve the original order of the list elements and render them in a specific order, use the function sorted(). The function sorted () allows you to display list elements in a specific order without affecting their original order in the list.

Next, try calling this function on the car list.

cars = ['bmw', 'audi', 'toyota', 'subaru']
❶ print("Here is the original list:") 
print(cars)
❷ print("\nHere is the sorted list:") 
print(sorted(cars))
❸ print("\nHere is the original list again:") 
print(cars)

We first print the list in the original order (see ❶), and then display the list in alphabetical order (see ❶). After the list is displayed in a specific order, we verify that the list elements are arranged in the same order as before (see ❸).

Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
❹ Here is the original list again: 
['bmw', 'audi', 'toyota', 'subaru']

Note that after calling the function sorted (), the order of the list elements does not change (see ❹). If you want to display the list in reverse alphabetical order, you can also pass the parameter reverse=True to the function sorted().

Note that the alphabetical list is more complex when not all values are lowercase. There are many ways to interpret capital letters when determining the order of arrangement. Specifying the exact order of arrangement may be better than what we do here
More complicated. However, most sorting methods are based on the knowledge introduced in this section.

3.3 print list upside down

To reverse the order of the list elements, use the method reverse(). Assuming that the car list is arranged according to the purchase time, you can easily arrange the cars in the reverse order:

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
print(cars)
cars.reverse() 
print(cars)

Note that reverse() does not mean that the list elements are arranged in the reverse alphabetical order, but just reverses the order of the list elements:

['bmw', 'audi', 'toyota', 'subaru']
 ['subaru', 'toyota', 'audi', 'bmw']

The method reverse() permanently modifies the arrangement order of the list elements, but can be restored to the original arrangement order at any time. To do this, just call reverse() on the list again.

3.4 determining the length of the list

Use the function len() to quickly learn the length of the list. In the following example, the list contains 4 elements, so its length is 4:

>>> cars = ['bmw', 'audi', 'toyota', 'subaru'] 
>>> len(cars)
4

len() is useful when you need to complete the following tasks: determining how many aliens have not been shot, how many visual data you need to manage, how many registered users there are on the website, etc.

Note that Python starts with 1 when calculating the number of list elements, so you should not encounter a difference error when determining the length of the list.

4, Avoid index errors when using lists

When you start using lists, you often encounter an error. Suppose you have a list of three elements and ask for the fourth element:

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles[3])

This will result in an index error:

Traceback (most recent call last):
File "motorcycles.py", line 3, in <module>
print(motorcycles[3]) IndexError: list index out of range

Python tries to provide you with an element at index 3, but when it searches the list motorcycles, it finds no element at index 3. This error is common due to the fact that the list index is one difference. Some people count from 1, so they think the index of the third element is 3; But in Python, the index of the third element is 2 because the index starts at 0.

An index error means Python cannot understand the index you specified. When the program has an index error, please try to reduce the index you specified by 1, and then run the program again to see if the result is correct.

Don't forget to use index - 1 whenever you need to access the last list element. This works in any case, even if the length of the list changes the last time you access it:

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles[-1])

Index-1 always returns the last list element. Here is the value 'suzuki':

'suzuki'

This way of accessing the last element causes an error only when the list is empty:

motorcycles = [] 
print(motorcycles[-1])

The list motorcycles does not contain any elements, so Python returns an index error message:

Traceback (most recent call last):
File "motorcyles.py", line 3, in <module>
print(motorcycles[-1]) IndexError: list index out of range

Note when an index error occurs but no solution is found, try printing the list or its length. The list may be very different from what you think, especially when the program processes it dynamically. By looking at the list or the number of elements it contains, you can help you find this logical error.

Topics: Python