Chapter 3
learning target:
What a list is and how to use list elements. Lists let you store groups of information in one place, which can contain only a few elements or millions of elements. Lists are one of the most powerful Python features that novices can use directly, and it incorporates many important programming concepts.
3.1 What is a list
A list consists of a series of elements arranged in a specific order. You can create all letters of the alphabet, numbers 0-9, or
A list of all family members' names; you can also add anything to the list, and there can be no relationship between the elements.
Given that lists often contain multiple elements, assigning a name to a list that represents a plural (such as letters, digits, or names) is
A good idea.
In Python, use square brackets [] to denote a list, and use commas to separate its elements.
E.g:
bicycles.py
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialired’]
print (bicycles)
# Results:
[‘Trek’, ‘cannondale’, ‘redline’, ‘specialired’]
3.1.1 Access List Elements
A list is an ordered collection, so to access any element of the list, just tell Python the position 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, extract the first bicycle from the list bicycles
bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialired’]
print (bicycles [0])
# Results:
trek
# Of course, or you can use the method title () to make the element ‘trek’ more neat:
print (bicycles [0] .title ())
# The output of this example is the same as the previous example, except that the initial letter T is capitalized.
3.1.2 Retrieval starts from 0 instead of 1
In Python, the index of the first list element is 0, not 1. This is true in most programming languages.
The underlying implementation of table operations is related.
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 the index as -1, you can make Python return
Back to the last list element:
print (bicycles [-1])
These codes return 'specialized'. This syntax is useful because you often need to know the length of the list
Access the last element. This convention also applies to other negative indices, for example, index-2 returns the penultimate list element,
Index -3 returns the third-to-last list element, and so on.
3.1.3 Using individual values in a list
You can use the individual values in the list as you would any other variable. For example, you can use stitching to create from values in a list
Message.
Let's try to extract the first bike from the list and use this value to create a message:
message = "My first bicycle was a" + bicycles [0] .title () + "."
print (message)
# Results:
My first bicycle was a Trek.
Try it yourself
Try writing some short programs to complete the exercises below to get some first steps using Python lists
First-hand experience. You may need to create a folder for the exercises in each chapter and store them in a neat and organized way
Program written in chapter exercises.
3-1 Names: Store the names of some friends in a list and name them names. Visit in turn
Each element in the list, which prints the names of each friend.
names = [‘zhangsan’, ‘lisi’, ‘wangwu’, ‘zhaoliu’]
print (names [0])
print (names [1])
print (names [-2])
print (names [-1])
# Results:
zhangsan
lisi
wangwu
zhaoliu
3-2 Greeting: Continue to use the list in Exercise 3-1, but instead of printing the name of each friend, type
Print a message. Each message contains the same greeting, but with the name of the corresponding friend.
messname1 = "Hi" + names [0] .title () + "."
messname2 = "Hi" + names [1] .title () + "."
messname3 = "Hi" + names [2] .title () + "."
messname4 = "Hi" + names [3] .title () + "."
print (messname1)
print (messname2)
print (messname3)
print (messname4)
# Results:
Hi Zhangsan.
Hi Lisi.
Hi Wangwu.
Hi Zhaoliu.
3-3 Your Own List: Think about your favorite way of commuting, such as riding a motorcycle or driving a car, and create an include
List of multiple commuting options. Use this list to print a series of declarations about these commuting methods, such as "I would like
to own a Honda motorcycle. "
bicycles = [‘bike’, ’electric car’, ‘motorbike’, ’car’]
mess1 = "I want to buy an" + bicycles [1] .title () + "."
print (mess1)
# Results:
I want to buy an Electric Car.
3.2 Modify, add and delete elements
Most lists created will be dynamic, which means that once the list is created, elements will be added and deleted as the program runs. For example: you create a game that requires players to shoot down aliens from the sky; for this, you can store some aliens in the beginning
List, and then every time an alien is shot, it is removed from the list, and every time a new alien appears on the screen
, They are added to the list. The length of the alien list will change throughout the game.
3.2.1 Modifying List Elements
The syntax for modifying list elements is similar to the syntax for accessing list elements. To modify a list element, specify the list name and the name to be modified
The index of the element, and specify the new value for that element.
E.g:
motorcycles.py
-----------------------------------------
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print (motorcycles)
motorcycles [0] = ‘ducati’
print (motorcycles)
-----------------------------------------
[‘Honda’, ‘yamaha’, ‘suzuki’]
[‘Ducati’, ‘yamaha’, ‘suzuki’]
3.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,
Add visual data or add new registered users to the site. Python provides multiple ways to add new data to an existing list.
Add element to the end of the list
When adding a new element to the list, the easiest way is to append the element to the end of the list. When appending an element to a list, it will
Add to the end of the list. Continuing with the list from the previous example, add a new element ‘ducati’ at the end:
motorcycles.append (‘ducati’)
print (motorcycles)
---------------------------------------
[‘Ducati’, ‘yamaha’, ‘suzuki’, ‘ducat’]
# Method append () adds element ‘ducati’ to the end of the list without affecting all other elements in the list
The method append () makes it easy to create lists dynamically. For example, you can create an empty list first, and then use a series of
The append () statement adds elements. 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)
-----------------------------
[‘Honda’, ‘yamaha’, ‘suzuki’]
This way of creating lists is extremely common, because you often have to wait for the program to run before you know where the user will store it in the program
Some data. To control the user, you can first create an empty list that stores the values that the user will enter, and then
Each new value is appended to the list.
Insert element into list
Use the insert () method to add new elements anywhere in the list. To do this, you need to specify the index and value of the new element.
motorcycles.insert (0, ‘ducati‘)
print (motorcycles)
---------------------------------------
[‘Ducati’, ‘honda’, ‘yamaha’, ‘suzuki’]
# In this example, the value ‘ducati’ is moved in and out of the list; the method insert () adds space at index 0 and stores the value ‘ducati’ there. This operation places each element already in the list one position to the right.
3.2.3 Remove elements from the list
You often need to remove one or more elements from a list. For example, after a player shoots an alien in the air, you can
Can remove it from the list of surviving aliens; when a user logs out of their account in a web application you create, you need to
The user is removed from the active user list. You can remove elements from a list based on their position or value.
Delete element using del statement
# Know the position of the list of elements to delete, you can use the del statement
motorcycles = [‘ducati’, ‘honda’, ‘yamaha’, ‘suzuki’]
del motorcycles [0]
print (motorcycles)
-----------------------------
[‘Honda’, ‘yamaha’, ‘suzuki’]
Remove element using method pop ()
Sometimes you want to remove an element from a list and then use its value. For example, you may need to get
The x and y coordinates of the alien in order to show the explosion effect at the corresponding position; in a web application, you may
Remove from the active member list and add it to the inactive member list.
The method pop () removes the element at the end of the list and lets you use it next. The term pop comes from such a class
Ratio: A list is like a stack, and deleting the end of the list is equivalent to popping the top element of the stack.
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print (motorcycles)
popped_motorcycle = motorcycles.pop ()
print (motorcycles)
print (popped_motorcycle)
------------------------------------------
[‘Honda’, ‘yamaha’, ‘suzuki’]
[‘Honda’, ‘yamaha’]
suzuki
How does the method pop () work? Assuming the motorcycles in the list are stored by time of purchase, you can use the method
pop () prints 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 last motorcycle I owned was a Suzuki.
Element anywhere in the popup list
You can use pop () to remove elements anywhere in the list, Just specify the element to delete in parentheses
Index.
first_owned = motorcycles.pop (0)
print ("The last motorcycle I owned was a" + first_owned.title () + ".")
-------------------------------------------------- -----------------------
The last motorcycle I owned was a Honda.
If you are not sure whether to use the del statement or the pop () method, here is a simple criterion: if you want to select from a list
Delete an element, and no longer use it in any way, use the del statement; if you want to continue after deleting the element
To use it, use the method pop ().
Remove elements based on value
Sometimes you don't know where the value you want to remove from the list is. If you only know the value of the element you want to delete, you can make
Use the method remove ().
# Suppose we want to delete the value `` ducati '' from the list motorcycles
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]
motorcycles.remove (‘ducati’)
print (motorcycles)
-------------------------------------------------- ---
[‘Honda’, ‘yamaha’, ‘suzuki’]
When you use remove () to remove an element from the list, you can then use its value. Let ’s delete the value ‘ducati’ and print a
Messages stating why they should be removed from the list:
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]
too_expensive = ‘ducati’
motorcycles.remove (too_expensive)
print (motorcycles)
print ("\ nA" + too_expensive.title () + "is too expensive for me.")
-------------------------------------------------- -----------------
[‘Honda’, ‘yamaha’, ‘suzuki’]
A Ducati is too expensive for me.
Note The method remove () only deletes the first specified value. If the value to be deleted may appear multiple times in the list, you need
Use a loop to determine if all such values have been deleted. You will learn how to do this in Chapter 7.
Try it yourself
The following exercises are more complicated than the exercises in Chapter 2, but give you the opportunity to use them in the various ways introduced earlier
List.
3-4 guest list: if you can invite anyone to dinner (whether alive or dead),
Who do you invite? Please create a list of at least 3 people you want to invite; then, use this
A list prints a message inviting these people to dinner with you.
dinner = []
dinner.append (‘zhangsan’)
dinner.append (‘lisi’)
dinner.append (‘wangwu’)
print (dinner)
---------------------------------------
[‘Zhangsan’, ‘lisi’, ‘wangwu’]
3-5 Revise the guest list: You just learned that a guest cannot go to the appointment, so you need to invite another guest.
dinner = []
dinner.append (‘zhangsan’)
dinner.append (‘lisi’)
dinner.append (‘wangwu’)
print (dinner)
dinner [1] = ‘zhaoliu’
print (dinner)
--------------------------------
[‘Zhangsan’, ‘lisi’, ‘wangwu’]
[‘Zhangsan’, ‘zhaoliu’, ‘wangwu’]
Based on the program you wrote when you completed Exercise 3-4, add a print statement at the end of the program to indicate which
Guests cannot make appointments.
dinner = []
dinner.append (‘zhangsan’)
dinner.append (‘lisi’)
dinner.append (‘wangwu’)
print (dinner)
no_dinner = dinner.pop (1)
print (no_dinner + "Can't make appointment")
---------------------------------
[‘Zhangsan’, ‘lisi’, ‘wangwu’]
Lisi is unable to make an appointment
Revise the guest list, and replace the names of guests who are not available for appointment with the names of newly invited guests.
dinner = []
dinner.append (‘zhangsan’)
dinner.append (‘lisi’)
dinner.append (‘wangwu’)
print (dinner)
no_dinner = dinner.pop (1)
dinner.insert (1, 'zhaoliu')
print (dinner)
--------------------------------
[‘Zhangsan’, ‘lisi’, ‘wangwu’]
[‘Zhangsan’, ‘zhaoliu’, ‘wangwu’]
Print a series of messages again to invite each guest on the list.
.... the above code is omitted
print (dinner [0])
print (dinner [1])
print (dinner [2])
--------------------
zhangsan
zhaoliu
wangwu
3-6 Adding Guests: You just found a larger table that can accommodate more guests. Please think about you also invite
Which three guests please.
Based on the program you wrote when you completed Exercise 3-4 or Exercise 3-5, add a print statement at the end of the program
Sentence, pointing out that you have found a larger dining table.
print ("Found a bigger table")
------------------------------
Found a bigger dining table
Use insert () to add a new guest to the beginning of the list.
dinner.insert (0, ‘xiaoming’)
print (dinner)
---------------------------------------------
[‘Xiaoming’, ‘zhangsan’, ‘zhaoliu’, ‘wangwu’]
Use insert () to add another new guest to the list.
dinner.insert (2, ‘xiaofang’)
print (dinner)
-------------------------------------------------- -------
[‘Xiaoming’, ‘zhangsan’, ‘xiaofang’, ‘zhaoliu’, ‘wangwu’]
Use append () to add the last new guest to the end of the list.
dinner.append (‘xiaowu’)
print (dinner)
-------------------------------------------------- -----------------
[‘Xiaoming’, ‘zhangsan’, ‘xiaofang’, ‘zhaoliu’, ‘wangwu’, ‘xiaowu’]
Print a series of messages and invite each guest on the list.
print ("Invite:" + dinner [0])
print ("Invite:" + dinner [1])
print ("Invite:" + dinner [2])
print ("Invite:" + dinner [3])
print ("Invite:" + dinner [4])
print ("Invite:" + dinner [5])
-----------------------------
Invitation: xiaoming
Invitation: zhangsan
Invitation: xiaofang
Invitation: zhaoliu
Invitation: wangwu
Invitation: xiaowu
3-7 Shortened list: You just learned that the newly purchased table cannot be delivered in time, so you can only invite two guests.
Based on the program you wrote when you completed exercises 3-6, add a line of code at the end of the program and print a
News that two guests can be invited to dinner.
print ("Only two guests can be invited to dinner!")
Use pop () to continuously delete guests from the list until there are only two guests. Every time from the list
When a guest is out, a message is printed to let the guest know that you are sorry and cannot invite him to join
dinner.
no_dinner = dinner.pop ()
print ("I ‘m sorry" + no_dinner)
no_dinner = dinner.pop ()
print ("I ‘m sorry" + no_dinner)
no_dinner = dinner.pop ()
print ("I ‘m sorry" + no_dinner)
no_dinner = dinner.pop ()
print ("I ‘m sorry" + no_dinner)
-------------------------------
I ’m sorry xiaowu
I ’m sorry wangwu
I ’m sorry zhaoliu
I ’m sorry xiaofang
For each of the two remaining guests, a message was printed stating that he was still among the invitees.
print (dinner)
------------------------
[‘Xiaoming’, ‘zhangsan’]
Use del to remove the last two guests from the list and make the list empty. Print the list and verify the process
The list was indeed empty at the end of the sequence.
del dinner [0]
del dinner [0]
print (dinner)
-------------
[]
3.3 Organization List
The order of the elements in the lists you create is often unpredictable, because you don't always control the user-supplied data
Order. Although this is unavoidable 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 organized columns
The form of the table can be selected according to the specific situation.
3.3.1 Use the sort () method to sort the list permanently
The Python method sort () makes it easier to sort a list. Suppose you have a list of cars and want to make it
The cars in alphabetical order. To simplify this task, we assume that all values in this list are lowercase.
cars.py
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort ()
print (cars)
-----------------------------------
[‘Audi’, ‘bmw’, ‘subaru’, ‘toyota’]
The # method sort () permanently changes the sort order of the list elements.
# Cars are now arranged in alphabetical order, and can no longer be restored to the original order
You can also arrange the list elements in reverse order alphabetically, for this, just pass parameters to the sort () method
reverse = True. The following example sorts the list of cars in reverse alphabetical order:
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort (reverse = True)
print (cars)
-----------------------------------
[‘Toyota’, ‘subaru’, ‘bmw’, ‘audi’]
3.3.2 Use the sorted () function to temporarily sort the list
To preserve the original order of the list elements while rendering it in a specific order
We can use the function sorted (). function
sorted () allows you to display list elements in a specific order without affecting their original sort order in the list.
Let's 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)
--------------------------------------------
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 the sort order of the list elements has not changed after calling the sorted () function. If you want to press the letter
The list is displayed in the reverse order. You can also pass the reverse = True parameter to the sorted () function.
Note When not all values are lowercase, sorting the list alphabetically is more complicated. When deciding order
The way to interpret capital letters, to specify the exact order, may be more complicated than what we do here. however,
Most sorting methods are based on the knowledge presented in this section.
3.3.3 Print the list upside down
To reverse the order of the list elements, use the method reverse (). Assuming the car list is sorted by time of purchase,
You can easily arrange the cars in the reverse order:
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print (cars)
cars.reverse ()
print (cars)
-----------------------------------------
[‘Bmw’, ‘audi’, ‘toyota’, ‘subaru’]
[‘Subaru’, ‘toyota’, ‘audi’, ‘bmw’]
Note that reverse () does not refer to arranging the list elements in the reverse order of the alphabetical order.
Column order.
The reverse () method permanently changes the order of the list elements, but can return to the original order at any time.
Just call reverse () on the list again.
3.3.4 Determine 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: determine how many aliens have not been shot and how many need to be managed
Item visual data, how many registered users the site has, etc.
Note that Python counts the number of elements in a list starting from 1, so you shouldn't encounter a difference when determining the length of a list.
Try it yourself
3-8 Look at the world: Think of at least 5 places you want to travel.
[] Store these places in a list and make sure that the elements are not in alphabetical order.
toponymy = [‘thailand’, ‘Singapore’, ‘japanese’, ‘egypt’, ‘america’]
The list is printed in the original order. Don't worry about whether the output is tidy, just print the original Python list.
print (toponymy)
-------------------------------------------------- --------
[‘Thailand’, ‘Singapore’, ‘japanese’, ‘egypt’, ‘america’]
[] Use sorted () to print this list alphabetically without modifying it.
print (sorted (toponymy))
-------------------------------------------------- -------
[‘America’, ‘egypt’, ‘japanese’, ‘singapore’, ‘thailand’]
[] Print the list again and verify that the sort order has not changed.
print (toponymy)
-------------------------------------------------- -------
[‘Thailand’, ‘singapore’, ‘japanese’, ‘egypt’, ‘america’]
[] Use sorted () to print this list in reverse order, and don't modify it.
toponymy = [‘thailand’, ‘japanese’, ‘singapore’, ‘egypt’, ‘america’]
print (sorted (toponymy, reverse = True))
-------------------------------------------------- --------------
[‘Thailand’, ‘singapore’, ‘japanese’, ‘egypt’, ‘america’]
Print the list again and verify that the sort order has not changed.
print (toponymy)
-------------------------------------------------- -------
[‘Thailand’, ‘japanese’, ‘singapore’, ‘egypt’, ‘america’]
Use reverse () to modify the sort order of the list elements. Print the list and verify that the sort order does change.
toponymy = [‘thailand’, ‘japanese’, ‘singapore’, ‘egypt’, ‘america’]
print ("Original list:")
print (toponymy)
toponymy.reverse ()
print ("\ nModify the list:")
print (toponymy)
-------------------------------------------------- -------
Original list:
[‘Thailand’, ‘japanese’, ‘singapore’, ‘egypt’, ‘america’]
Modify the list:
[‘America’, ‘egypt’, ‘singapore’, ‘japanese’, ‘thailand’]
Use reverse () to change the sort order of the list elements again. Print the list and verify that it has returned to its original sort order.
toponymy.reverse ()
print ("\ nModify the following list again:")
print (toponymy)
-------------------------------------------------- ---------
Modify the following list again:
[‘Thailand’, ‘japanese’, ‘singapore’, ‘egypt’, ‘america’]
Use sort () to modify the list so that its elements are sorted alphabetically. Print the list and verify that the sort order does change.
toponymy = [‘thailand’, ‘japanese’, ‘singapore’, ‘egypt’, ‘america’]
toponymy.sort ()
print (toponymy)
-------------------------------------------------- -------
[‘America’, ‘egypt’, ‘japanese’, ‘singapore’, ‘thailand’]
Use sort () to modify the list so that its elements are sorted in reverse order from alphabetical order. Print the list and verify that the sort order does change.
toponymy = [‘thailand’, ‘japanese’, ‘singapore’, ‘egypt’, ‘america’]
toponymy.sort ()
print (toponymy)
toponymy.sort (reverse = True)
print (toponymy)
-------------------------------------------------- --------
[‘America’, ‘egypt’, ‘japanese’, ‘singapore’, ‘thailand’]
[‘Thailand’, ‘singapore’, ‘japanese’, ‘egypt’, ‘america’]
3-9 Dinner guests: In one of the programs written when completing exercises 3-4 ~ 3-7, use len () to print a message indicating how many guests you invited to dinner with you.
>>> cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
>>> len (cars)
4
3-10 Try using functions: Think of things that can be stored in a list, such as mountains, rivers, countries, cities, languages, or anything you like. Write a program that creates a list containing these elements, and then use each of the functions described in this chapter at least once to process the list.
name = [‘mount everest’, ‘yellow river’, ‘beijing’, ‘china’]
print (name)
print ("\ nTemporary sort:")
print (sorted (name))
print ("\ nTemporary reverse order:")
print (sorted (name, reverse = True))
print ("\ nSort alphabetically:")
name.sort (reverse = True)
print (name)
print ("\ nSort alphabetically:")
name.sort ()
print (name)
print ("\ nPrint upside down:")
name.reverse ()
print (name)
print ("\ nNumber of elements:")
print (len (name))
print ("\ nNumber of elements:% d"% len (name))
-------------------------------------------------- --------
[‘Mount everest’, ‘yellow river’, ‘beijing’, ‘china’]
Temporary sorting:
[‘Beijing’, ‘china’, ‘mount everest’, ‘yellow river’]
Temporary reverse ordering:
[‘Yellow river’, ‘mount everest’, ‘china’, ‘beijing’]
Sort alphabetically reverse:
[‘Yellow river’, ‘mount everest’, ‘china’, ‘beijing’]
Sort alphabetically:
[‘Beijing’, ‘china’, ‘mount everest’, ‘yellow river’]
Printing upside down:
[‘Yellow river’, ‘mount everest’, ‘china’, ‘beijing’]
Number of elements:
4
Number of elements: 4
Python basics list introduction, use