Notes on Python programming from introduction to practice (Part II. List)

Keywords: Python

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"]

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"]


3.1.2 using list elements

colours = ["blue","red","yellow","oranges"]
print("My favoutite colour is "+colours[-2])

My favoutite colour is yellow




#3.2 greetings
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!

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']
# Modify the list element and reassign it directly
# Add elements to the list
# Add to end
# Using append to create a list
motocycles = []
# 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']
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']
peo_list.insert(1,"foxy") # ['lewis', 'foxy', 'gracie']
# 3-6 add guests
print("I find a bigger table.")
print(peo_list) # ['gigi', 'lewis', 'foxy', 'gracie']

# ==============================================================================================
# Sort list contents permanent: sort
cars =['bmw','audi','toyota','subaru']
print(cars) # ['audi', 'bmw', 'subaru', 'toyota']
# reverse
cars =['bmw','audi','toyota','subaru']
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']
print(place) # ['exeter', 'wuhan', 'tai', 'emei']
print(place) # ['emei', 'tai', 'wuhan', 'exeter']
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:
# 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
# 1
# 2
# 3
# 4

# Using range() to create a list of values
numbers = list(range(1,6))
# [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):
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:
# 4-4 output digital elements
nums = list(range(1,10000))
for num in nums:
# 4-5 calculation sum
a = list(range(1,100001))
print(sum(a)) # 5000050000
# 4-6 odd numbers
for a in range(1,21,2):
# 4-7 even numbers
for b in range(2,21,2):
# Numbers divisible by 3, print numbers
for c in range(3,31,3):
# Cube of integer within 10
for d in range(1,11):
# Analysis of cube
ds = [d**3 for d in range(1,11)]

# 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]:

# 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:")
# 3 of them
# The latter 3
# Copy list
my_pizza = ["bacon","carrot","mashrooms"]
friend_pizza = my_pizza[:]
# loop
for item in my_pizza:

# Tuple - immutable list
# Define tuple
diamensions = (200,50)
# Traverse tuples
for diamension in diamensions:
# Change tuple variable = redefine instead of changing the original tuple
diamensions = (30,500)
for diamension in diamensions:
diamensions = (400,20)
for diamension in diamensions:
Published 2 original articles, won praise 1 and visited 37
Private letter follow

Posted by ma9ic on Tue, 03 Mar 2020 22:31:07 -0800