python Programming (from introduction to practice) Chapter 3

Chapter III list introduction

What is the list

A list consists of a series of elements arranged in a specific order. There is no relationship between multiple elements. A list usually contains multiple elements. Therefore, assign a name representing a plural number to the list (such as letters, digits, or names).

In python, the list is represented by square brackets ([]) and the elements are separated by commas. Here is a simple example,

vim bicycles.py
bicycles = ['trek','cannondale','specialized']
print(bicycles)

implement

python3 bicycles.py
['trek', 'cannondale', 'specialized']
Access list elements

A list is an ordered collection, so to access any element of the list, you only need to tell python the location (index) of the element. To access a list element, indicate the name of the list, then the index of the element, and place it in curly braces;

When you request a list element, python returns only that element, not square brackets;

Index starts at 0 instead of 1

In python, the index of the first list element is 0 instead of 1 Most programming languages are so specified that it is related to the underlying implementation of list operations.

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

Execute and return the second element in the list

python3 bicycles.py
cannondale
Cannondale

python provides a special element for accessing the last list element. By specifying an index of - 1, you can have python return the last list element.

python3 bicycles.py
specialized

This method is useful because you often need to access the last element without knowing the length of the list. This Convention also applies to negative indexes. For example, index - 2 returns the penultimate list element, index - 3 returns the penultimate list element, and so on.

Use individual values in the list

You can use the values in the list just like other variables. For example, you can use the f string to create a message based on the values in the list.

bicycles = ['trek','cannondale','specialized']
messages = f"My first bicycle was a {bicycles[0].title()}."

print(messages)

We use the value of bicycles[0] to generate a sentence and assign it to the variable messages. The output is a simple sentence.

implement

python3 bicycles.py
My first bicycle was a Trek.

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.

Modify 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 to be modified.

For example, suppose there is a motorcycle list, in which the first element is' honda ', how to modify its value?

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

motorcycles[0] = 'ducati'
print(motorcycles)

First, define a motorcycle list, in which the first element is' handa ' Next, change the value of the first element to 'ducati'. The output shows that the value of the first element has indeed changed, but the values of other list elements have not changed:

python3 mororcycles.py
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

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

Add an element 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 existing lists.

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 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('dducati')
print(motorcycles)

The method append() adds the element 'ducati' to the list without affecting other list elements.

implement

python3 mororcycles.py
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'dducati']

The method append() makes it easy to create a list dynamically. For example, you can create an empty list and use a series of function calls append() to add elements., Next, you will create an empty list and add a series of elements to it.

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

print(motorcycles)

This method of creating lists is very 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 value provided by the user to the list.

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. The method insert() adds space at index 0 and stores the value 'ducati' there. This operation moves each existing element in the list to the right one position;

python3 mororcycles.py
['ducati', 'honda', 'yamaha', 'suzuki']
Remove element from list

You need to remove 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 out of the 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.

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)

implement

python3 mororcycles.py
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
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 in order to display the explosion effect in the response 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.

motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
poped_motorcycles =  motorcycles.pop()
print(motorcycles)
print(poped_motorcycles)

First, define and print the values of the list motorcycles. Next, pop up a value from this list and assign it to popped_ motorcycles . The list is then printed to verify that a value has been removed from it. Finally, the printed value pops up to prove that we can still access the deleted value. The output shows that the value 'suzuki' at the end of the list has been deleted and is now assigned to the variable popped_ motorcycles.

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
The value of the element anywhere in the pop-up list

In fact, you can use pop() to delete an element anywhere in the list. Just specify the index to be deleted in parentheses. Use the f string to create a complete piece of information by associating the variable with the information.

motorcycles = ['honda','yamaha','suzuki']
first_motorcycles = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_motorcycles.title()}")

First pop up the first element of the list through pop(), and then print out a simple sentence related to that element.

implement

python3 mororcycles.py
The first motorcycle I owned was a Honda
Delete element based on value

Sometimes you don't know where the value you want to delete from the list is. If you only know the value to delete, you can use the method remove().

Delete the value 'ducati' from the list of motorcycles.

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

motorcycles.remove('ducati')
print(motorcycles)

remove() 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 also use its value next. Below, delete the value 'ducati' and print a message indicating the reason for deleting it from the list:

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

motorcycles.remove(too_expensive)
print(motorcycles)
print(f"\nA {too_expensive.title()} is too expensive for me.")

After defining the list motorcycles, assign the value 'ducati' to the variable too_expensive. Next, use this variable to tell python which value to remove from the list. Finally, the value 'ducati' has been removed from the list, but can be changed through the variable too_expensive to access it. We printed a message.

implement

python3 mororcycles.py
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

A Ducati is too expensive for me.

The method remove() deletes only the first specified value. If the value to be deleted may appear more than once in the list, you need to use the for loop to ensure that each value is deleted. This will be described in Chapter 7.

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. But you often need to present the order in a specific order. python provides many ways to organize the list, which can be selected according to the specific situation.

Use the post method sort() to permanently sort the list

The python method sort() allows you to sort the list more easily. Suppose you have a list of cars in alphabetical order. All list elements are lowercase.

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

The method sort() permanently arranges the list cars.

implement

python3 cars.py
['audi', 'bmw', 'subaru', 'toyota']

You can also arrange the list elements in reverse alphabetical order by passing the parameter reverse=True to the sort() method.

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

implement

python3 cars.py
['toyota', 'subaru', 'bmw', 'audi']
Temporarily sort the list using the method sorted()

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.

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

print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("Here is the original list again:")
print(cars)

If you want to display the list in reverse alphabetical order, you can also pass the parameter reverse=True to the function sorted().

implement

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']
Print the list upside down

To reverse the order of the list elements, use the method reverse().

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

print(cars)
cars.reverse()
print(cars)

Instead of arranging the list elements in a list in the reverse alphabetical order, the method reverse() is used to reverse the order of the list:

python3 cars.py
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

The method reverse() permanently modifies the arrangement order of the list elements, but it can be restored to the original arrangement order at any time. You only need to call reverse() on the list again.

Determines the length of the list

Use the function len() to quickly learn the length of the list. In the following example, the list contains four 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, determining how many visual data you need to manage, calculating how many users have registered on the website, and so on.

Note that python starts with 1 when calculating list elements, so you shouldn't encounter a difference error when determining the length of the list.

Avoid index errors when using lists

When you start using lists, you often encounter an error. If you have a list of three elements and ask for the fourth element, this will lead to an index error. Don't forget that when accessing a list element, you can use index - 1 This works in any case, even if the length of the list changes the last time you access it. The index always returns the last list element. This access method will cause an error only when the list element is empty.

Keywords: Python Linux Back-end

Added by ClanCC on Sun, 23 Jan 2022 02:00:01 +0200