Chapter 3 list introduction, chapter 3 list Introduction

Source: Internet
Author: User

Chapter 3 list introduction, chapter 3 list Introduction

The list is a very important part. In Python, the list, Dictionary, function, class, and class are mainly composed of functions with various functions, as long as you understand the list, Dictionary nature, and methods, and then understand the calling principles of functions, how to call parameters, and lay a solid foundation for these operations, in the future, it will be of great benefit to your entire learning process.

3.1 What is the list

List: composed of a seriesSpecific order. We can create a list containing all letters, numbers 0-9, or names of all family members in the alphabet, or add anything to the list without any relationship between the elements. Given that a list usually contains multiple elements, creating a plural name for the List (such as names, letters, and usres) is a good note.

In Python, square brackets ([]) are used to represent the list and commas are used to separate the elements.

Note: The list is ordered and arranged in a specific order. You must remember this because only when you understand the list order can you understand why to call the elements in the list, and calling principles. In addition, this is the unique nature of the list.

Bicycles. py

Bicycles = ["trek", "cannodale", "redline", 'speciaized']
Print (bicycles)

Results:

['Trek', 'cannodale ', 'redline', 'speciaized']

3.1.1 access list elements

The list is an ordered set consisting of elements arranged in a specific order. Therefore, to access the elements in the list, you only need to tell Python the position or index of the element. To access the list element, you can specify the name of the list, index the element, and put it in square brackets.

3.1.2 index starts from 0 instead of 1

In Python, the index of the first list element is 0 rather than 1. This is true in most programming languages, which is related to the underlying implementation of list operations. If the result is unexpected, check whether the error is a simple one.

The index of the second list element is 1. According to this simple counting method, any element in the list to be accessed can be reduced by 1 and the result is used as the index.

Python provides a special syntax for accessing the last list element. By specifying the index as-1, Python can return the last list element, for example, bicycles [-1 ".

This syntax is useful because we often need to access the final element without knowing the list length. This Convention applies to other negative indexes. For example, index-2 returns the second-to-second list element, index-3 returns the third-to-last list element, and so on.

3.1.3 use values in the list

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

Next we will try to extract the first bicycle from the list and use this value to create a message:

Bicycles = ["trek", "cannodale", "redline", 'speciaized']
Message = "My first bicycle was a" + bicycles [0]. title () + "."
Print (message)

We use the value of bicycles [0] to generate a sentence and store it in the variable message. The output is a simple sentence that contains the first bicycle in the list.

My first bicycle was a Trek.

Try it

3-1 Name:Store the names of some friends in a list and name them names. To access each element in the list and print out the names of each friend.

3-2 greetings:Continue to use the list in Exercise 3-1, but print a message for everyone without the name of each friend. Each message contains the same greeting, but the name of the corresponding friend is displayed.

3-3 your own list:Think about your favorite commuting methods, such as riding a motorcycle or driving a car, and create a list containing multiple commuting modes. Print a series of declarations about commuting methods based on the list, such as "I wowould like to own a Honda motorcycle ".

Analysis:

3-1The main purpose of this question is to traverse every element in the list. First, define a list and then traverse each list.

Names = ["tom", "zengmignzhu", "gengchangxue", "dlj"]
Print (names [0])
Print (names [1])
Print (names [2])
Print (names [3])

First, a list is defined and then each element in the list is traversed. The output result is as follows:

Tom
Zengmignzhu
Gengchangxue
Dlj

It can be seen that the list is ordered, and it must be kept in mind that the expression of the list, the list name plus the index number, add the index number in brackets.

3-2This question is an improvement of the first question and an output name. It only needs to use the merging function to exercise the merging function.

 

Names = ["tom", "zeng mign zhu", "geng chang xue", "dlj"]
Print (names [0]. title () + "is my great firend .")
Print (names [1]. title () + "is a excellent student .")
Print (names [2]. title () + "is my girl friend .")
Print (names [3]. title () + "is my good friend ")
Result output:
Tom is my great firend.
Zeng Mign Zhu is a excellent student.
Geng Chang Xue is my girl friend.
Dlj is my good friend

3-3This topic also describes how to call the list and concatenate strings.

Commuting_modes = ["by car", "ride motorcycle", "on foot", 'by bus']

3.2 modify, add, and delete Elements

Most of the list we create is dynamic, which means that after the list is created, it will add and delete elements as the program runs. For example, we create a game that requires players to shoot aliens who fall from the sky. To this end, some aliens can be stored in the list at the beginning, and each time an alien is shot, are removed from the list, and each time a new alien appears on the screen, it is added to the list. The length of the alien list will change throughout the game.

3.2.1 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:

 

Motorcycles = ['honda', 'yamha ', 'suzuki']
Print (motorcycles)

Motorcycles [0] = "ducati"
Print (motorcycles)
First, we define a motorcycle list. The first element is "Honda ". Next, we will change the value of the first element to 'ducata '. The output result is as follows:
['Honda', 'yamha', 'suzuki ']
['Ducata', 'yamha ', 'suzuki']
We can modify the elements at any position in the list as long as we know the location and purpose of the modification.
3.2.2 add elements to the list
We may add new elements to the list out of applications. For example, you want new aliens to appear in the game, add visualization data or add new registered users to the website. Python provides a variety
You can add new elements to the list.
1. Add an element at the end of the list
When adding a new element to the list, the simplest way is to append the element to the end of the list. When an element is added to the list, it is added to the end of the list. Method append () to add an element at the end of the list.
Method append ():
Append (...)
L. append (object) -- append object to end (add an element at the end of the list)
Motorcycles. py
motorcycles = ['honda','yamha','suzuki']
motorcycles.append()
print(motorcycles)
motorcycles.append("ducati")
print(motorcycles)
Note: I have never used append () to add an empty parameter. If the parameter is omitted, the program reports an error as follows:
Traceback (most recent call last ):
File "/home/zhuzhu/title3/motorcycles. py", line 2, in <module>
Motorcycles. append ()
TypeError: append () takes exactly one argument (0 given)
The cause of the error is that the method append () does not have a parameter. The append () method must have a parameter, but (0 given) does not have a parameter. Therefore, the system reports an error.
When a parameter is added to append (), it is as follows:
Motorcycles = ['honda', 'yamha ', 'suzuki']
# Motorcycles. append ()
Print (motorcycles)
Motorcycles. append ("ducati ")
Print (motorcycles)
Results:
['Honda', 'yamha', 'suzuki ']
['Honda', 'yamha', 'suzuki ', 'ducata']
This time, we added "ducatati" to the end of the list without an error.
Motorcycles = ['honda', 'yamha ', 'suzuki']
Motorcycles. append ("")
Motorcycles. append ("")
Print (motorcycles)
Motorcycles. append ("ducati ")
Print (motorcycles)

Results:
['Honda', 'yamha', 'suzuki ', '','']
['Honda', 'yamha ', 'suzuki', '','', 'ducata']
When we add blank text and spaces to the program, the program can run normally, and the results also contain ''and" ", indicating that as long as the append () method has parameters, the system will not report errors without Parameters
Program errors.
The append () method makes it easy to dynamically create a list. For example, we can create an empty list first and then use a series of append () statements to add elements. Create an empty list, and then add
Elements "honda", "yamha", and "suzuki ":
Motorcycles = []
Motorcycles. append ("honda ")
Motorcycles. append ("yamha ")
Motorcycles. append ("suzuki ")
Print (motorcycles)
The running result is as follows:
['Honda', 'yamha', 'suzuki ']
Motorcycles = ["honda", "yamha", "suzuki"]
Motorcycles. insert (0, "ducati ")
Print (motorcycles)
# Now there are four elements. Let's take a look at the results of table out-of-bounds under "tables ".
Motorcycles. insert (7, "sb ")
Motorcycles. insert (-7, "bs ")
Print (motorcycles)

Running result:
['Ducata', 'honda', 'yamha ', 'suzuki']
['Bs ', 'ducata', 'honda', 'yamha', 'suzuki ', 'SB']
From the running results, we can add new elements at the position we set. As long as the index and value of the new elements are determined, we also verify that the superscripts and subscripts are out of bounds. We can see that, whether the above-mentioned mark is out of bounds
If the subscript is out of bounds, the program does not report an error, but runs normally. The subscript superfield adds an element at the last position, and the superfield adds the element at the beginning.

Summary: There are two ways to insert an element into the list. The first is to add an element at the end of the append () method. The append () parameter of this method must exist, and no parameter is required, can add any
Any element, '', and" "can be used, but the parameter cannot be omitted without specifying a location. It is useful when generating a new list. insert () the method is to add an element anywhere in the list, insert ()
There are two parameters in the method, and neither of them can be left blank. You must specify a value for both parameters at the time of insertion. If you are interested, you can try it and the up and down mark can be out of bounds, if you want to start with the list
To add an element, you only need to execute L. insert (0, object) to add the element at the beginning of the list. This is a supplement to the append () method. More importantly, when the list is empty
When using the insert () method in the list, no error is reported. This is really powerful. When using this method, we do not have to worry about the cross-border uplink and downlink, you do not have to worry about the use process, if
The list is empty.
Add new elements to the list. These two methods can be used very well. They are both good for actual use.
Motorcycles = []
# Motorcycles. insert (0, "ducati ")
Print (motorcycles)
# Now there are four elements. Let's take a look at the results of table out-of-bounds under "tables ".
Motorcycles. insert (7, "sb ")
Motorcycles. insert (-7 ,"")
Print (motorcycles)
Running result:
[]
['', 'SB ']
It can be seen that the insert () method is still very powerful, empty, and there is no program error in the cross-border. You can use it with confidence.

3.2.3 delete an element from the list
We not only often add elements to the list, but also often delete one or more elements from the list. For example, after a gamer kills an alien in the air
It is very likely to be deleted from the list of living aliens. When a user cancels his/her account in the Web application you created, we also need to delete the user from the active list. We can delete the data by location or value.
List elements. (Location and value) We know the location of the deleted element or the element to be deleted.
1. Use the del statement to delete an element.
If you know where to delete an element in the list, you can use the del statement.
Motorcycles = ["honda", "yamha", "suzuki"]
Print (motorcycles)
# Delete the value of The 0th position in the list
Del motorcycles [0]
Print (motorcycles)

Running result:
['Honda', 'yamha', 'suzuki ']
['Yamha ', 'suzuki']
We know that we want to delete the 0th position element, so we use del to delete the value of The 0th position in the list. del is used by del + L. [I].
Del can be used to delete list elements in any position, provided that we know its position in the list, that is, its index. The following describes how to delete the second element in the preceding list-"yamaha ":
Motorcycles = ["honda", "yamha", "suzuki"]
Print (motorcycles)
# Delete the value of The 0th position in the list
Del motorcycles [1]
Print (motorcycles)
Running result:
['Honda', 'yamha', 'suzuki ']
['Honda', 'suzuki ']
We can see that using del to delete a list element requires us to know the specific position of the element in the list, that is, the index. Del + L [I]
After an element is deleted from the list using the del method, this value does not exist in the list, and we cannot access it.
Next, let's try out the above and below:
Motorcycles = ["honda", "yamha", "suzuki"]
Print (motorcycles)
# Delete the value of The 0th position in the list
Del motorcycles [-5]
Del motorcycles [5]
Print (motorcycles)
Running result:
['Honda', 'yamha', 'suzuki ']
Traceback (most recent call last ):
File "/home/zhuzhu/title3/motorcycles. py", line 4, in <module>
Del motorcycles [-5]
IndexError: list assignment index out of range
From the results, we can see that the index has a problem (IndexError). The cause of the index error is that the index is out of bounds. Therefore, when using del to delete an element, you must know the specific position of the element, and then
If the list is empty, an error is returned, unlike the insert () method.

2. Use pop () to delete an element
Pop (...)
| L. pop ([index])-> item -- remove and return item at index (default last ).
| Raises IndexError if list is empty or index is out of range.
According to the description of the pop () method, the pop () method removes and returns elements from a list and returns them to another variable. If the list is empty, or the index is out of bounds.
Sometimes, we need to delete the element from the list and then use it. For example, we may need to obtain the x and y coordinates of the newly shot aliens to display the explosive effect at the corresponding position. In Web applications,
Users may be deleted from the list of active members and added to the list of inactive members.
The pop () method deletes the element at the end of the list and allows us to continue using it. TermsPop-upPop is derived from a list like a stack. Deleting the elements at the end of the list is equivalent to popping up the top elements of the stack.
A motorcycle is displayed in the motorcycles list below:
Motorcycles = ["honda", "yamha", "suzuki"]
Print (motorcycles)
# Pop up a new element from the list and assign it to poped_motorcycle, and then use it
Poped_motorcycle = motorcycles. pop ()
Print (motorcycles)
Print (poped_motorcycle)
Running result:
['Honda', 'yamha', 'suzuki ']
['Honda', 'yamha ']
Suzuki





 
 







 
 



 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.