Chapter 3 list
3.1 what is a list
- A list consists of a series of elements arranged in a specific order.
- There can be no relationship between the elements
- It's a good idea to give a list a plural name, such as letters, digits, or names.
- Use square brackets ([]) to represent the list and comma to separate its elements
letters = ["a","b","r","g","1"] print(letters)
The print list will also print out square brackets
['a', 'b', 'r', 'g', '1']
3.1.1 access list elements
With the access list element, you can print out the output you want the user to see. A list is an ordered collection, so to access any element of a list, simply tell Python the location or index of that element. Location starts at 0
letters = ["a","b","r","g","1"] print(letters[0]) print(letters[-1])
a
1
3.1.2 using list elements
colours = ["blue","red","yellow","oranges"] print("My favoutite colour is "+colours[-2])
My favoutite colour is yellow
Practice:
#3.1 names=["Gracie","Foxy","Lewis","Mia"] print(names[0]) print(names[1]) print(names[2]) print(names[3])
Gracie
Foxy
Lewis
Mia
#3.2 greetings names=["gracie","foxy","lewis","mia"] print(names[0].title()+" , nice to meet you!") print(names[1].title()+" , nice to meet you!") print(names[2].title()+" , nice to meet you!") print(names[3].title()+" , nice to meet you!")
Gracie , nice to meet you!
Foxy , nice to meet you!
Lewis , nice to meet you!
Mia , nice to meet you!
#3.3 trans = ["Honda","Benz","jili"] print("I would like to own a "+trans[0])
I would like to own a Honda
3.2 modifying, adding and deleting 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.
e.g for example, you create a game where players are required to shoot aliens falling from the sky; to do this, you can store some aliens in the list at the beginning, and then delete them from the list every time they are shot, and add new aliens to the list every time they appear on the screen. The length of the alien list will change throughout the game.
# Original list motocycles =['honda','yamaha','suzuki'] print(motocycles) # Modify the list element and reassign it directly motocycles[0]='ducati' # Add elements to the list # Add to end motocycles.append('ducati') # Using append to create a list motocycles = [] motocycles.append('honda') motocycles.append('yamaha') motocycles.append('suzuki') # insert an element anywhere in the list motocycles =['honda','yamaha','suzuki'] motocycles.insert(0,'ducati')# Insert 'duati' at list 0 # Delete element in list # Method 1: del motocycles =['honda','yamaha','suzuki'] # Delete the element of the list location 0 with the keyword del del motocycles[0] # Method 2: pop(), pop(), removes the element from the list and then uses its value. # If you need to get the x and y coordinates of the alien you just shot in order to produce an explosive effect in the corresponding location, you may need to delete the user from the active member list and then put it in the inactive list # The pop() method removes 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 an element at the end of the list is equivalent to popping up the top of the stack (last in, first out). motocycles = ['a','b','c','d'] popped_motocycles = motocycles.pop() print(motocycles) # ['a', 'b', 'c'] print(popped_motocycles) # d # 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 # Delete anywhere popped_motocycles = motocycles.pop(1) # Don't know the location, delete according to the value: remove motocycles = ['a','b','c','d'] motocycles.remove("a") print(motocycles) # ['b', 'c', 'd'] # **remove can only delete the first one. To delete all the required loops # 3-4 create list peo_list = ['lewis','mia','gracie'] print(peo_list) # ['lewis', 'mia', 'gracie'] # 3-5 modification of guest list print(peo_list[1]+" cannot arrive.") # mia cannot arrive. peo_list.remove("mia") # ['lewis', 'gracie'] print(peo_list) peo_list.insert(1,"foxy") # ['lewis', 'foxy', 'gracie'] print(peo_list) # 3-6 add guests print("I find a bigger table.") peo_list.insert(0,"gigi") print(peo_list) # ['gigi', 'lewis', 'foxy', 'gracie'] # ============================================================================================== # Sort list contents permanent: sort cars =['bmw','audi','toyota','subaru'] cars.sort() print(cars) # ['audi', 'bmw', 'subaru', 'toyota'] # reverse cars =['bmw','audi','toyota','subaru'] cars.sort(reverse=True) print(cars) # ['toyota', 'subaru', 'bmw', 'audi'] # Sort temporarily cars =['bmw','audi','toyota','subaru'] print(cars) # ['bmw', 'audi', 'toyota', 'subaru'] print(sorted(cars)) # ['audi', 'bmw', 'subaru', 'toyota'] print(cars) # ['bmw', 'audi', 'toyota', 'subaru'] print(sorted(cars,reverse=True)) # ['toyota', 'subaru', 'bmw', 'audi'] # Inverted list cars =['bmw','audi','toyota','subaru'] a = cars.reverse() # You can't type print(cars.reverse) directly. I don't know why print(cars) # ['subaru', 'toyota', 'audi', 'bmw'] # Calculate list length cars =['bmw','audi','toyota','subaru'] print(len(cars)) # 4 # 3-8 5 places to visit place = ['emei','tai','wuhan','exeter'] print(place) # ['emei', 'tai', 'wuhan', 'exeter'] print(sorted(place)) # ['emei', 'exeter', 'tai', 'wuhan'] print(place) # Order of ['emei ',' Tai ',' Wuhan ',' Exeter '] remains unchanged print(sorted(place,reverse = True)) # ['wuhan', 'tai', 'exeter', 'emei'] place.reverse() print(place) # ['exeter', 'wuhan', 'tai', 'emei'] place.reverse() print(place) # ['emei', 'tai', 'wuhan', 'exeter'] place.sort() print(place) # ['emei', 'exeter', 'tai', 'wuhan'] place.sort(reverse= True) print(place) # ['wuhan', 'tai', 'exeter', 'emei']
3.4 avoid indexing errors
When the array is out of bounds, you can first check the length of the list.
=============================================================================
Chapter IV operation list
# Traversal list: perform the same operation on all elements in the list. In this case, the complex number of waiting list is very important and easy to understand # Print out all the names names = ['Alice','Jone','Jennie','Lisa','Rose'] for name in names: print(name) # Operation result # Alice # Jone # Jennie # Lisa # Rose # After the for loop, code without indentation is executed only once, without repeated execution magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() + ".\n") print("Thank you, everyone. That was a great magic show!") # Alice, that was a great trick! # I can't wait to see your next trick, Alice. # David, that was a great trick! # I can't wait to see your next trick, David. # Carolina, that was a great trick! # I can't wait to see your next trick, Carolina. # Thank you, everyone. That was a great magic show! # expected an indented block # Unnecessary indent error: unexpected indent # At the same time, pay attention to logical errors # 4-1 pizzas = ["tomato", "bacon", "seafood", "potato"] for pizza in pizzas: print("I like " + pizza + " pizza") # I like tomato pizza # I like bacon pizza # I like seafood pizza # I like potato pizza for pizza in pizzas: print("I like "+ pizza + " pizza") print("I really like pizza") # I like potato pizza # I like tomato pizza # I like bacon pizza # I like seafood pizza # I like potato pizza # I really like pizza # Create a list of values for val in range(1,5): # Left and right open print(val) # 1 # 2 # 3 # 4 # Using range() to create a list of values numbers = list(range(1,6)) print(numbers) # [1, 2, 3, 4, 5] # Specified Steps even_numbers = list(range(2,11,2)) odd_numbers = list(range(1,11,2)) print(even_numbers) # [2, 4, 6, 8, 10] print(odd_numbers) # [1, 3, 5, 7, 9] # List contains the square of an integer within 10 squares = [] for num in range(1,11): squares.append(num**2) print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # Find the maximum, minimum, and total of the list digits = list(range(1,15)) print(min(digits)) # 1 print(max(digits)) # 14 print(sum(digits)) # 105 # List parsing # List parsing merges the for loop and the code that creates the new element into one line and automatically appends the new element. squares = [value**2 for value in range(1,11)] print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # 4-3 nums = list(range(1,21)) for num in nums: print(num) # 4-4 output digital elements nums = list(range(1,10000)) for num in nums: print(list) # 4-5 calculation sum a = list(range(1,100001)) print(sum(a)) # 5000050000 # 4-6 odd numbers for a in range(1,21,2): print(a) # 4-7 even numbers for b in range(2,21,2): print(b) # Numbers divisible by 3, print numbers for c in range(3,31,3): print(c) # Cube of integer within 10 for d in range(1,11): print(d**3) # Analysis of cube ds = [d**3 for d in range(1,11)] print(ds) # Use a part of the list to process some elements of the list -- slicing players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) # ['charles', 'martina', 'michael'] # Take 2-4 elements print(players[1:4]) # ['martina', 'michael', 'florence'] # Start from scratch print(players[:4]) # ['charles', 'martina', 'michael', 'florence'] # End at end print(players[2:]) # ['michael', 'florence', 'eli'] # Several post harvest print(players[-3:]) # ['michael', 'florence', 'eli'] # Traversal slice - some elements in the convenience list players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("Here are the first three players on my team:") for player in players[:3]: print(player.title()) # Copy list my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] # If we simply assign my food to friend food, we cannot get two lists. my_foods = ['pizza', 'falafel', 'carrot cake'] #This will not work. friend_foods = my_foods # Instead of storing a copy of my food in friend food, assign my food to friend food. # This syntax actually allows Python to associate the new variable friend'foods with the list contained in my'foods, so these two # Variables all point to the same list. In view of this, when we add 'cannoli' to my food, it will also appear in the # Friend_foods; similarly, although 'ice cream' seems to be only added to friend_foods, it will also appear here # Two lists. # 4-10 vegetables = ["tomato","potato","carret","carrot","peanut"] # Why can't the first three be tied up in the same print print("The first three items in the lists are:") print(vegetables[:3]) # 3 of them print(vegetables[1:4]) # The latter 3 print(vegetables[-3:]) # Copy list my_pizza = ["bacon","carrot","mashrooms"] friend_pizza = my_pizza[:] my_pizza.append("beef") friend_pizza.append("seafood") print(my_pizza) print(friend_pizza) # loop for item in my_pizza: print(item) # Tuple - immutable list # Define tuple diamensions = (200,50) print(diamensions[0]) # Traverse tuples for diamension in diamensions: print(diamention) # Change tuple variable = redefine instead of changing the original tuple diamensions = (30,500) for diamension in diamensions: print(diamension) diamensions = (400,20) for diamension in diamensions: print(diamension)