跪拜 Guibai
← Back to the summary

A Frontend Lead's Day 3 of Switching to AI Agent Engineering: Python Data Structures

Learning Path

Python -> Advanced Python -> Python Data Analysis -> LangChain -> Machine Learning -> Neural Networks -> NLP -> Coze -> Dify -> LLM Application Basics -> LLM Fine-tuning -> Multimodal -> vibeCoding

Python Learning

60. Lists_Defining Lists

# Define a list with content
# list = [34, 56, 21, 56, 11]  # Cannot override built-in functions
list1 = [34, 56, 21, 56, 11]
list2 = ['Beijing', 'Shang Silicon Valley', 'Hello']
list3 = [23, 'Shang Silicon Valley', True, None]
list4 = [23, 'Shang Silicon Valley', True, None, [100, 200, 300]]
print(list1, type(list1))
print(list2, type(list2))
print(list3, type(list3))
print(list4, type(list4))

# Define an empty list (data will be filled later using specific methods)
list5 = []
list6 = list()
print(list5, type(list5))
print(list6, type(list6))

61. Lists_Subscripts (Index Values)

# Define a list
nums = [10, 20, 30, 40, 50]

# Test positive indexing
print(nums[0])
print(nums[1])
print(nums[2])
print(nums[3])
print(nums[4])

# Test negative indexing
print(nums[-1])
print(nums[-2])
print(nums[-3])
print(nums[-4])
print(nums[-5])

# Test incorrect index
# print(nums[5])  # Error

# Define a nested list
nums = [10, 20, ['Hello', 'Shang Silicon Valley'], 40, 50]
# Extract "Shang Silicon Valley"
print([nums[2]])
print([nums[2][1]])

62. Lists_CRUD Operations

# Add operations
# Method 1: Use the list's append method to add an element to the end of the list
from unittest import result

nums = [10, 20, 30, 40]
nums.append(50)
print(nums)

# Method 2: Use the list's insert method to add an element at a specified index
nums = [10, 20, 30, 40]
nums.insert(2, 666)
print(nums)

# Method 3: Use the list's extend method to take items from an iterable and append them to the end of the list
nums = [10, 20, 30, 40]
nums.extend('Shang Silicon Valley')
print(nums)  # [10, 20, 30, 40, 'Shang', 'Silicon', 'Valley']
nums.extend(range(1, 4))
print(nums)  # [10, 20, 30, 40, 'Shang', 'Silicon', 'Valley', 1, 2, 3]
x = nums.extend([70, 80, 90])
print(nums)  # [10, 20, 30, 40, 'Shang', 'Silicon', 'Valley', 1, 2, 3, 70, 80, 90]
print(x)  # None

# Delete operations
# Method 1: Use the list's pop method to remove an element at a specified position and return that element
nums = [10, 20, 10, 40, 50]
result = nums.pop(1)
print(nums)  # [10, 10, 40, 50]
print(result)  # 20

# Method 2: Use the list's remove method to delete the first occurrence of a specified value
nums = [10, 20, 10, 40, 50]
nums.remove(10)
print(nums)  # [20, 10, 40, 50]

# Method 3: Use the list's clear method to delete all elements in the list (empty the list)
nums = [10, 20, 10, 40, 50]
nums.clear()
print(nums)  # []

# Method 4: Use the del keyword to delete a specified element
nums = [10, 20, 10, 40, 50]
del nums[3]
print(nums)  # [10, 20, 10, 50]

# Modify operation
nums = [10, 20, 10, 40, 50]
nums[2] = 66
print(nums)  # [10, 20, 66, 40, 50]

# Query operation
nums = [10, 20, 10, 40, 50]
print(nums[3])  # 40

63. Lists_Common Methods

# 1. Use the index method to find the first occurrence index of a specified element in the list. Return value: element index
fruits = ['Banana', 'Apple', 'Orange', 'Banana']
result = fruits.index('Banana')
print(result)  # 0
result = fruits.index('Apple')
print(result)  # 1
# result = fruits.index('Strawberry')  # Runtime error
# print(result)
fruits = ['Banana', 'Apple', 'Orange', 'Banana', ['Strawberry', 'Pineapple']]
# result = fruits.index('Strawberry')  # Runtime error, does not search deeper
# print(result)

# 2. Use the count method to count the number of occurrences of an element in the list. Return value: number of occurrences
nums = [10, 20, 10, 30, 10, 40]
result = nums.count(10)
print(result)  # 3
result = nums.count(66)
print(result)  # 0
nums = [10, 20, 10, 30, 10, 40, [10, 10, 10]]
result = nums.count(10)
print(result)  # 3, does not search deeper

# 3. Use the reverse method to reverse the list (modifies the original list)
nums = [23, 11, 32, 30, 17]
nums.reverse()
print(nums)  # [17, 30, 32, 11, 23]
nums = [23, 11, 32, 30, 17, [6, 7, 8, 9]]
nums.reverse()
print(nums)  # [[6, 7, 8, 9], 17, 30, 32, 11, 23], does not reverse deeper

# 4. Use the sort method to sort the list (ascending by default). For descending, set the reverse parameter to True
# 4.1 If all elements are numbers, sorts by numerical order
nums = [23, 11, 32, 30, 17]
nums.sort()
print(nums)  # [11, 17, 23, 30, 32]
nums.sort(reverse=True)
print(nums)  # [32, 30, 23, 17, 11]

# 4.2 If elements contain both numbers and strings, an error occurs
nums = [23, 11, 32, 30, 17, 'Shang Silicon Valley']
# nums.sort()  # Runtime error
# print(nums)

# 4.3 If all elements are strings, sorts by Unicode code point order
msg_list = ['Beijing', 'Shang Silicon Valley', 'Hello']
msg_list.sort()
print(msg_list)  # ['Hello', 'Beijing', 'Shang Silicon Valley']
print(ord('你'), ord('北'), ord('尚'))
msg_list = ['Beijing', 'North Silicon Valley', 'North Good']
msg_list.sort()
print(msg_list)  # ['Beijing', 'North Good', 'North Silicon Valley']
print(ord('京'), ord('好'), ord('硅'))

# Note: All list methods only operate on the "current level" elements (shallow operation) and do not automatically enter nested "inner" structures

64. Lists_Common Built-in Functions

# 1. Use the built-in sorted function to return a sorted new container (does not modify the original container, default order: ascending)
# 1.1 If all elements are numbers, sorts by numerical order
nums = [23, 11, 32, 30, 17]
result = sorted(nums)
print(nums)  # [23, 11, 32, 30, 17]
print(result)  # [11, 17, 23, 30, 32]
result = sorted(nums, reverse=True)
print(nums)  # [23, 11, 32, 30, 17]
print(result)  # [32, 30, 23, 17, 11]

# 1.2 If elements contain both numbers and strings, an error occurs
nums = [23, 11, 32, 30, 17, 'Shang Silicon Valley']
# sorted(nums)  # Runtime error

# 1.3 If all elements are strings, sorts by Unicode code point order
msg_list = ['Beijing', 'Shang Silicon Valley', 'Hello']
result = sorted(msg_list)
print(msg_list)  # ['Beijing', 'Shang Silicon Valley', 'Hello']
print(result)  # ['Hello', 'Beijing', 'Shang Silicon Valley']

# 2. Use the built-in len function to get the total number of elements in a container. Return value: total number of elements
nums = [10, 20, 10, 30, 10, 40]
result = len(nums)
print(result)  # 6
nums = [10, 20, 10, 30, 10, 40, [50, 60, 70]]
result = len(nums)
print(result)  # 7

# 3. Use the built-in max function to get the maximum value in a container. Return value: maximum value
# 3.1 If all elements are numbers, max returns the largest number
nums = [23, 11, 32, 30, 17]
result = max(nums)
print(nums)
print(result)  # 32

# 3.2 If elements contain both numbers and strings, max will error
nums = [23, 11, 32, 30, 17, 'Shang Silicon Valley']
# result = max(nums)  # Runtime error
# print(result)

# 3.3 If all elements are strings, max returns the character with the largest Unicode code point
msg_list = ['Beijing', 'Shang Silicon Valley', 'Hello']
result = max(msg_list)
print(msg_list)
print(result)  # 'Shang Silicon Valley'

# 3.4 The max function can also receive multiple values and select the maximum
result = max(33, 45, 12, 78, 99)
print(result)  # 99

# 4. Use the built-in min function to get the minimum value in a container. Return value: minimum value
# Note: The usage and caveats of the min function are the same as max, except min returns the minimum value
nums = [23, 11, 32, 30, 17]
result = min(nums)
print(result)  # 11

# 5. Use the built-in sum function to sum the data in a container (elements must be numeric)
nums = [10, 20, 30, 40, 50]
result = sum(nums)
print(result)  # 150
nums = [10, 20, 30, 40, 50, 'Shang Silicon Valley']
# result = sum(nums)  # Runtime error
# print(result)
nums = [10, 20, 30, 40, 50, [60, 70, 80]]
# result = sum(nums)  # Runtime error
# print(result)
msg = 'Hello'
# result = sum(msg)  # Error
# print(result)
msg = '123456'
# result = sum(msg)  # Error
# print(result)

65. Lists_Loop Iteration

# Define a score list
score_list = [62, 50, 60, 48, 80, 20, 95]

# Use a while loop to iterate over the list
index = 0
while index < len(score_list):
    # print(index)
    print(score_list[-index])
    index += 1

# index = 1  # Index out of bounds
# while index <= len(score_list):
#     print(score_list[index])
#     index += 1

# A self-made method to prevent index out of bounds
index = 1
while index <= len(score_list):
    print(score_list[-index])
    index += 1

# Use a for loop to iterate over the list
for item in score_list:
    print(item)

# Use a for loop to iterate over the list by index using the range and len functions
for index in range(len(score_list)):
    # print(index)
    print(score_list[index])

# Use a for loop to iterate over the list using the enumerate function to get both index and element
for index, item in enumerate(score_list):
# The start parameter of enumerate can make the count start from a specified value (changes the "number" during iteration, not the actual index)
# for index, item in enumerate(score_list, start=5):
    print(index, item)
    # print(index, item, score_list[0])
print(enumerate(score_list), type(enumerate(score_list)))  # Self-exploration
print(f'Final print {score_list[0]}')

66. Lists_Small Exercise

# My own version
def input_score():
    score_list = []
    while True:
        score = input('Please enter a score (enter "end" to finish input): ')
        if score == 'end':
            break
        elif int(score) < 0 or int(score) > 100:
            print('Please enter a number between 0 and 100')
        else:
            score_list.append(int(score))
    return score_list

def get_nums(score_list):
    passed_num = 0
    great_num = 0
    for score in score_list:
        if score >= 60:
            passed_num += 1
        if score >= 90:
            great_num += 1
    return [passed_num, great_num]

def get_computed(score_list):
    score_list_len = len(score_list)
    print(f'Total students: {score_list_len}')
    print(f'Highest score: {max(score_list)}')
    print(f'Lowest score: {min(score_list)}')
    computed_get_nums = get_nums(score_list)
    print(f'Pass count: {computed_get_nums[0]}')
    print(f'Pass rate: {computed_get_nums[0] / score_list_len}')
    print(f'Excellent count: {computed_get_nums[1]}')
    print(f'Excellent rate: {computed_get_nums[1] / score_list_len}')
    print(f'Average score: {sum(score_list) / score_list_len}')

def main():
    scores = input_score()
    if scores:
        get_computed(scores)
    else:
        print('Please re-enter scores')
        main()

main()

# Teacher's approach
print('Please enter student scores, enter "end" to stop recording')
score_list = []

# Continuous loop, let the user input student scores
while True:
    data = input('✍Please enter a score: ')
    if data == 'end':
        break
    else:
        score_list.append(int(data))

# If score_list has data, start statistics
if score_list:
    # print('Specific statistics code')
    # Calculate average score
    avg = sum(score_list) / len(score_list)
    # Pass count
    pass_count = 0
    # Excellent count
    excellent_count = 0
    # Iterate over the list, start counting
    for item in score_list:
        if item >= 60:
            pass_count += 1
        elif item >= 90:
            excellent_count += 1
    # Pass rate
    pass_rate = pass_count / len(score_list) * 100
    # Excellent rate
    excellent_rate = excellent_count / len(score_list) * 100
    # Print information
    print('*********👇Statistics info below👇*********')
    print(f'👮Total students: {len(score_list)}')
    print(f'👆Highest score: {max(score_list)}')
    print(f'👇Lowest score: {min(score_list)}')
    print(f'Pass count: {pass_count} people')
    print(f'Pass rate: {pass_rate:.1f}%')
    print(f'🏆Excellent count: {excellent_count} people')
    print(f'Excellent rate: {excellent_rate:.1f}%')
    print(f'Average score: {avg:.1f}')
else:
    print('You did not enter any scores!')

67. Lists_Small Exercise

# My own version
def input_score():
    score_list = []
    while True:
        score = input('Please enter a score (enter "end" to finish input): ')
        if score == 'end':
            break
        elif int(score) < 0 or int(score) > 100:
            print('Please enter a number between 0 and 100')
        else:
            score_list.append(int(score))
    return score_list

def get_nums(score_list):
    passed_num = 0
    great_num = 0
    for score in score_list:
        if score >= 60:
            passed_num += 1
        if score >= 90:
            great_num += 1
    return [passed_num, great_num]

def get_computed(score_list):
    score_list_len = len(score_list)
    print(f'Total students: {score_list_len}')
    print(f'Highest score: {max(score_list)}')
    print(f'Lowest score: {min(score_list)}')
    computed_get_nums = get_nums(score_list)
    print(f'Pass count: {computed_get_nums[0]}')
    print(f'Pass rate: {computed_get_nums[0] / score_list_len}')
    print(f'Excellent count: {computed_get_nums[1]}')
    print(f'Excellent rate: {computed_get_nums[1] / score_list_len}')
    print(f'Average score: {sum(score_list) / score_list_len}')

def main():
    scores = input_score()
    if scores:
        get_computed(scores)
    else:
        print('Please re-enter scores')
        main()

main()

# Teacher's approach
print('Please enter student scores, enter "end" to stop recording')
score_list = []

# Continuous loop, let the user input student scores
while True:
    data = input('✍Please enter a score: ')
    if data == 'end':
        break
    else:
        score_list.append(int(data))

# If score_list has data, start statistics
if score_list:
    # print('Specific statistics code')
    # Calculate average score
    avg = sum(score_list) / len(score_list)
    # Pass count
    pass_count = 0
    # Excellent count
    excellent_count = 0
    # Iterate over the list, start counting
    for item in score_list:
        if item >= 60:
            pass_count += 1
        elif item >= 90:
            excellent_count += 1
    # Pass rate
    pass_rate = pass_count / len(score_list) * 100
    # Excellent rate
    excellent_rate = excellent_count / len(score_list) * 100
    # Print information
    print('*********👇Statistics info below👇*********')
    print(f'👮Total students: {len(score_list)}')
    print(f'👆Highest score: {max(score_list)}')
    print(f'👇Lowest score: {min(score_list)}')
    print(f'Pass count: {pass_count} people')
    print(f'Pass rate: {pass_rate:.1f}%')
    print(f'🏆Excellent count: {excellent_count} people')
    print(f'Excellent rate: {excellent_rate:.1f}%')
    print(f'Average score: {avg:.1f}')
else:
    print('You did not enter any scores!')

68. Tuples

# Define tuples
from unittest import result

t1 = (28, 67, 21, 67, 11)
t2 = ('Beijing', 'Shang Silicon Valley', 'Hello')
t3 = (100, True, 'Hello', None)
t4 = (100, True, 'Hello', None, (50, 60, 70))
print(type(t1), t1)
print(type(t2), t2)
print(type(t3), t3)
print(type(t4), t4)

# Tuple subscripts
t1 = (28, 67, 21, 67, 11)
print(t1[3])
print(t1[-1])

# Elements in a tuple cannot be modified
# t1[0] = 100  # Error

# Elements in a tuple cannot be modified, but if a tuple contains a mutable type (list), the content of that mutable type can still be modified
t2 = (28, 67, 21, 67, 11, [100, 200, 300, ('Hello', 'Shang Silicon Valley')])
# t2[5] = 400  # Error
t2[5][2] = 400
print(t2)
# t2[5][3][0] = 'hello'  # Runtime error

# Define empty tuples
t1 = ()
t2 = tuple()
print(type(t1), t1)
print(type(t2), t2)

# Define a tuple with a single element
# t1 = ('Hello')  # Error
t1 = (
    'Hello',
    'Shang Silicon Valley'
)
print(type(t1), t1)  # Hello Shang Silicon Valley  Not a tuple, it's a string
t1 = ('Hello',)
t2 = (18,)
print(type(t1), t1)  # Is a tuple
print(type(t2), t2)  # Is a tuple

# Common methods
# index method: Get the first occurrence index of a specified element in the tuple
t1 = (28, 67, 21, 67, 11)
result = t1.index(67)
print(result)  # 1

# count method: Count the number of occurrences of a specified element in the tuple
t1 = (28, 67, 21, 67, 11)
result = t1.count(67)
print(result)  # 2

# Common built-in functions
# max function, returns the maximum value in the tuple
t1 = (23, 11, 32, 30, 17)
result = max(t1)
print(result)  # 32

# min function, returns the minimum value in the tuple
t1 = (23, 11, 32, 30, 17)
result = min(t1)
print(result)  # 11

# len function, returns the number of elements in the tuple (tuple length)
t1 = (23, 11, 32, 30, 17)
result = len(t1)
print(result)  # 5

# sorted function, sorts the tuple (does not modify the original tuple, returns a new list)
t1 = (23, 11, 32, 30, 17)
result = sorted(t1)
print(result)  # [11, 17, 23, 30, 32]
result = sorted(t1, reverse=True)
print(result)  # List [32, 30, 23, 17, 11]
print(tuple(result))  # Tuple (32, 30, 23, 17, 11)

# sum function, sums all elements in the tuple (elements must be purely numeric)
t1 = (23, 11, 32, 30, 17)
result = sum(t1)
print(result)  # 113

# In actual development, tuples are not necessarily defined by us. For example, the variable argument *args of a function is a tuple
def demo(*args):
    # print(args)
    return sum(args)
# demo(100, 200, 300)
result = demo(100, 200, 300)
print(result)  # 600

# Tuple loop iteration
t1 = (23, 11, 32, 30, 17)

# while loop iteration
index = 0
while index < len(t1):
    print(t1[index])
    index += 1

# for loop iteration
for item in t1:
    print(item)

69. Functions_Unpacking Lists or Tuples for Arguments


# def test(data):
# def test(a, b, c, d):
# When defining a function, use *args (the variable doesn't have to be named args, e.g., *data works too) to pack multiple received arguments into a tuple
def test(*args):
    # print(f'I am the test function, the arguments I received are: {data}')
    # print(f'I am the test function, the arguments I received are: {a}, {b}, {c}, {d}')
    print(f'I am the test function, the arguments I received are: {args}, argument type is: {type(args)}')
list1 = [100, 200, 300, 400]
tuple1 = ('Hello', 'Beijing', 'Shang Silicon Valley')

# When calling a function, pass normally: list or tuple
# test(list1)
# test(tuple1)

# When calling a function, use * to unpack a list or tuple before passing arguments
test(*list1)  # This is equivalent to: test(100, 200, 300, 400)  Error, too many arguments
test(*tuple1)  # This is equivalent to: test('Hello', 'Beijing', 'Shang Silicon Valley')  Error, too few arguments

70. Functions_Comprehensive Case (Optimized Version)

def calc_total(*nums):
# def calc_total(nums):
    """
    Calculate total exercise volume (reps)
    :param nums: Daily exercise volume (variable arguments)
    :return: Total exercise volume (reps)
    """
    return sum(nums)

def calc_avg(total, days=7):
    """
    Calculate average
    :param total: Total exercise volume (reps)
    :param days: Number of days (default is 7)
    :return: Average value
    """
    return total / days

def check_success(total, goal=120):
    """
    Check if this challenge is successful
    :param total: Total exercise volume
    :param goal: Success threshold (default is 120)
    :return: Specific success or failure message
    """
    if total >= goal:
        return 'Congratulations! Challenge successful!'
    else:
        return 'Sorry! Challenge failed!'

# def main(title, duration):
def main(title, duration, goal):
    """
    Main function, used to start a challenge
    :param title: Challenge title
    :param duration: Challenge duration in days
    :param goal: Target exercise volume
    :return: None
    """
    print(f'【{title}】【{duration} days】👊Challenge (Please enter daily reps)')
    # num1 = int(input('Day 1: '))
    # num2 = int(input('Day 2: '))
    # num3 = int(input('Day 3: '))
    # Define a nums list to store daily fitness data
    nums = []
    # Loop based on the duration value to let the user input
    for index in range(duration):
        nums.append(int(input(f'Please enter data for day {index + 1}: ')))

    # Calculate total
    # total = calc_total(num1, num2, num3)
    # total = calc_total(nums)
    total = calc_total(*nums)
    # Calculate average
    avg = calc_avg(total, duration)
    # Check if the challenge is successful
    result = check_success(total, 30)
    # Print relevant information
    print(f'【{title}】【{duration} days】Fitness Summary')
    print(f'Total: {total}, Average: {avg:.1f}')
    print(result)

main('Push-ups', 3, 40)

71. Strings (From a Data Container Perspective)

# String subscripts
from unittest import result

msg = 'welcome to atguigu'
print(msg[3])
print(msg[-1])

# Characters in a string cannot be modified
msg = 'welcome to atguigu'
# msg[0] = 'a'  # Error

# Strings cannot be nested
# msg = 'welcome to 'hello' atguigu'
msg = 'welcome to "hello" atguigu'
print(msg[11])  # 11
msg = 'welcome to 'hello' atguigu'

# Common methods
# index method: Get the first occurrence index of a specified character in the string
msg = 'welcom to atguigu'
result = msg.index('t')
print(result)  # 8

# split method: Split the string by a specified character and store the separated parts into a list
msg = 'Shang Silicon Valley@atguigu@Hello'
result = msg.index('@')
print(msg)  # 'Shang Silicon Valley@atguigu@Hello'
print(result)  # ['Shang Silicon Valley', 'atguigu', 'Hello']
result = msg.index('x')
print(result)  # ['Shang Silicon Valley@atguigu@Hello']
msg = 'welcome to atguigu'
result = msg.index(' ')
print(result)  # ['welcome', 'to', 'atguigu']

# replace method: Replace a certain character segment in the string with a target string (does not modify the original string, returns a new string)
msg = 'welcome to atguigu'
result = msg.replace('g', 'G')
print(msg)  # welcome to atguigu
print(result)  # welcome to atGuiGu
result = msg.replace('atguigu', 'Shang Silicon Valley')
print(result)  # welcome to Shang Silicon Valley

# count method: Count the number of occurrences of a specified character in the string
msg = 'welcome to atguigu'
result = msg.count('g')
print(result)  # 2

# strip method: Delete any character from a string that is in the specified character set
# Rule: Starts deleting from both ends of the string, stops as soon as it encounters a character not in the set
msg = '666Shang6Silicon6Valley666'
result = msg.strip('6')
print(msg)  # '666Shang6Silicon6Valley666'
print(result)  # 'Shang6Silicon6Valley'

msg = '1234Shang12Silicon34Valley4321'
result = msg.strip('1324')
print(msg)  # '1234Shang12Silicon34Valley4321'
print(result)  # 'Shang12Silicon34Valley'

msg = '34215Shang12Silicon34Valley4132'
result = msg.strip('5432')
print(msg)  # '34215Shang12Silicon34Valley4132'
print(result)  # '15Shang12Silicon34Valley41'

# Common use of strip
msg = '  Shang Silicon Valley  '
result = msg.strip()
print(msg)  # '  Shang Silicon Valley  '
print(result)  # 'Shang Silicon Valley'

# Common built-in functions
# len function: Count the number of characters in a string (string length)
msg = 'welcome to atguigu'
result = len(msg)
print(result)  # 18

# max, min, sorted can also be used but are basically meaningless

# String loop iteration
msg = 'welcome to atguigu'
# while loop iteration
index = 0
while index < len(msg):
    print(msg[index])
    index += 1

# for loop iteration
for item in msg:
    print(item)

72. Sequence Slicing Operations

# Slicing does not include the end position [start:end:step]
# start: default 0
# end: default sequence length
# step: default 1, if n, takes every n-1 elements
# If start > end, step must be negative

# Slice a list
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[0:5:1]
print(list2)  # [10, 20, 30, 40, 50]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[1:8:2]
print(list2)  # [20, 40, 60, 80]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[1:8:3]
print(list2)  # [20, 50, 80]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[0:10:1]
print(list2)  # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[::]
print(list2)  # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[:999:]
print(list2)  # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[3::]
print(list2)  # [40, 50, 60, 70, 80, 90, 100]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[:5:]
print(list2)  # [10, 20, 30, 40, 50]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[::4]
print(list2)  # [10, 50, 90]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[7:2:-1]
print(list2)  # [80, 70, 60, 50, 40]

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[7:2:1]
print(list2)  # []

# A special case: When both start and end indices are omitted and the step is negative, Python automatically swaps the start and end positions
list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list2 = list1[::-1]
print(list2)  # [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

# Slice a tuple
tuple1 = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
tuple2 = tuple1[0:5:1]
print(tuple2)  # (10, 20, 30, 40, 50)

# Slice a string
msg1 = 'welcome to atguigu'
msg2 = msg1[2:9:2]
print(msg2)  # 'loet'

73. Other Sequence Operations

# Sequence addition
list1 = [10, 20, 30, 40]
list2 = [50, 60, 70, 80]
list3 = list1 + list2
print(list3)  # [10, 20, 30, 40, 50, 60, 70, 80]

tuple1 = (10, 20, 30, 40)
tuple2 = (50, 60, 70, 80)
tuple3 = tuple1 + tuple2
print(tuple3)  # (10, 20, 30, 40, 50, 60, 70, 80)

str1 = 'hello'
str2 = 'atguigu'
str3 = str1 + str2
print(str3)  # 'hello atguigu'

# Error example
list1 = [10, 20, 30, 40]
str1 = 'hello'
# print(list1 + str1)  # Error

# Sequence multiplication (repetition)
list1 = [10, 20, 30, 40]
list2 = list1 * 3
print(list2)  # [10, 20, 30, 40, 10, 20, 30, 40, 10, 20, 30, 40]

tuple1 = (10, 20, 30, 40)
tuple2 = tuple1 * 3
print(tuple2)  # (10, 20, 30, 40, 10, 20, 30, 40, 10, 20, 30, 40)

str1 = 'hello'
str2 = str1 * 6
print(str2)  # 'hellohellohellohellohellohello'

2026.7.11 19:43

74. Sets_Defining Sets

# Define a [mutable set] with content
s1 = {10, 20, 20, 30, 40, 40, 50, 60, 60, 70, 80, 90, 100}
s2 = {'Hello', 'hello', 'Hello', 'atguigu', 'Beijing'}
# s3 = {10, 'Hello', 1, True, 12.4}
s3 = {10, 'Hello', True, 1, 12.4}
print(type(s1), s1)
print(type(s2), s2)
print(type(s3), s3)
s2.add('Shang Silicon Valley')
print(s2)

# Define an [immutable set] with content
s1 = frozenset({10, 20, 20, 30, 40, 40, 50, 60, 60, 70, 80, 90, 100})
s2 = frozenset({'Hello', 'hello', 'Hello', 'atguigu', 'Beijing'})
s3 = frozenset({10, 'Hello', True, 1, 12.4})
print(type(s1), s1)
print(type(s2), s2)
print(type(s3), s3)
# s2.add('Shang Silicon Valley')  # Error

# The parameter accepted by frozenset can be any iterable, but the final return is always an [immutable set]
s1 = frozenset([10, 20, 30, 40, 50])
s2 = frozenset((10, 20, 30, 40, 50))
s3 = frozenset('hello')
print(type(s1), s1)
print(type(s2), s2)
print(type(s3), s3)

# Define an empty set (mutable set)
s1 = set()
print(type(s1), s1)  # set set()

# Cannot directly write {} to define an empty set, because writing {} directly defines an empty dictionary
s2 = {}
print(type(s2), s2)  # dict {}

# Define an empty set (immutable set)
s3 = frozenset()
print(type(s3), s3)  # frozenset frozenset()

# A set cannot nest a [mutable set], but can nest an [immutable set]
# Plain explanation: Only "immutable" things can be safely placed into a set
s1 = {10, 20, 30, 40, 50}
s2 = frozenset({100, 200, 300, 400, 500})
l1 = [666, 777, 888]
l2 = ('hello', 'atguigu', 'Beijing')

# s3 = {11, 22, 33, s1}  # Runtime error
s3 = {11, 22, 33, s2}
# s3 = {11, 22, 33, l1}  # Runtime error
s3 = {11, 22, 33, l2}
print(s3)

75. Sets_CRUD Operations

# Add
# add method: Add an element to the set
from unittest import result

s1 = {10, 20, 30, 40, 50}
s1.add(60)
print(s1)

# update method: Add elements to the set (must pass an iterable, e.g., list, tuple, set, etc.)
s1 = {10, 20, 30, 40, 50}
s1.update([60, 70])
s1.update((80, 90))
s1.update({90, 100})
s1.update(range(300, 308))
print(s1)

# Delete
# remove method: Remove an element from the set (removing a non-existent element will cause an error)
s1 = {10, 20, 30, 40, 50}
s1.remove(20)
print(s1)
# s1.remove(80)  # Runtime error

# discard method: Remove an element from the set (removing a non-existent element will not cause an error)
s1 = {10, 20, 30, 40, 50}
s1.discard(20)
print(s1)
s1.discard(80)  # No error

# pop method: Remove an arbitrary element from the set, return value is the removed element
s1 = {10, 20, 30, 40, 50}
s2 = {'Hello', 'Beijing', 'Shang Silicon Valley', 'hello'}
result = s1.pop()
print(s1)
print(result)
result = s2.pop()
print(s2)
print(result)

# clear method: Clear the set
s1 = {10, 20, 30, 40, 50}
s1.clear()
print(s1)

# Modify
# Use a combination of add + remove to achieve a modification effect
s1 = {10, 20, 30, 40, 50}
s1.remove(20)
s1.add(66)
print(s1)

# Query: Sets cannot read elements by subscript, but can check if a set contains a specified element using [membership operators]
# Since membership operators apply to all data containers, we will discuss them after all data containers have been covered
s1 = {10, 20, 30, 40, 50}
# s1[0]  # Error
# Get a sneak peek at membership operators
result = 20 in s1
print(result)  # True
result = 20 not in s1
print(result)  # False

76. Sets_Common Methods

# SetA.difference(SetB):
# Purpose: Find elements in SetA that are different from SetB (SetA and SetB remain unchanged, returns a new set)
s1 = {10, 20, 30, 40, 50}
s2 = {30, 40, 50, 60, 70}
result = s1.difference(s2)
print(s1)
print(s2)
print(result)

# SetA.difference_update(SetB):
# Purpose: Delete elements from SetA that exist in SetB (SetA is modified, SetB is not)
s1 = {10, 20, 30, 40, 50}
s2 = {30, 40, 50, 60, 70}
s1.difference_update(s2)
print(s1)  # {10, 20}
print(s2)
s1 = {10, 20, 30, 40, 50}
s2.difference_update(s1)
print(s1)
print(s2)  # {70, 80}

# SetA.union(SetB)
# Purpose: Merge two sets, SetA and SetB remain unchanged, returns a new set
s1 = {10, 20, 30, 40, 50}
s2 = {30, 40, 50, 60, 70}
result = s1.union(s2)
print(s1)
print(s2)
print(result)
result = s2.union(s1)
print(s1)
print(s2)
print(result)

# SetA.issubset(SetB)
# Purpose: Determine if SetA is a subset of SetB
# If all elements of SetA are in SetB, returns True, otherwise returns False
s1 = {10, 20, 30, 40, 50}
s2 = {30, 40, 50, 60, 70}
s3 = {30, 40, 50}
result = s3.issubset(s1)
print(result)  # True
result = s3.issubset(s2)
print(result)  # True
result = s2.issubset(s1)
print(result)  # False

# SetA.issuperset(SetB)
# Purpose: Determine if SetA is a superset of SetB
# If SetA contains all elements of SetB, returns True, otherwise returns False
s1 = {10, 20, 30, 40, 50}
s2 = {30, 40, 50, 60, 70}
s3 = {30, 40, 50}
result = s1.issuperset(s3)
print(result)  # True
result = s2.issuperset(s3)
print(result)  # True
result = s2.issuperset(s1)
print(result)  # False

# SetA.isdisjoint(SetB)
# Purpose: Determine if SetA and SetB have no intersection
# If there is no intersection, returns True; if there is at least one common element, returns False
s1 = {10, 20, 30, 40, 50}
s2 = {30, 40, 50, 60, 70}
s3 = {80, 90}
result = s1.isdisjoint(s3)
print(result)  # True
result = s1.isdisjoint(s2)
print(result)  # False

77. Sets_Mathematical Operations

s1 = {10, 20, 30, 40, 50, 60}
s2 = {40, 50, 60, 70, 80, 90}

# Union
result = s1 | s2
print(result)  # {70, 40, 10, 80, 50, 20, 90, 60, 30}

# Intersection
result = s1 & s2
print(result)  # {40, 50, 60}

# Difference
result = s1 - s2
print(result)  # {10, 20, 30}
result = s2 - s1
print(result)  # {80, 90, 70}

# Symmetric difference
result = s1 ^ s2
print(result)  # {70, 10, 80, 20, 90, 30}

78. Sets_Loop Iteration

s1 = {10, 20, 30, 40, 50, 60}

# Sets cannot use while loop iteration (the following is an incorrect example)
index = 0
while index < len(s1):
    print(index)
    # print(s1[index])  # Error
    index += 1

# Sets can use for loop iteration
for item in s1:
    print(item)

79. Dictionaries_Defining Dictionaries

# Define a dictionary with content
d1 = {'Zhang San': 72, 'Li Si': 60, 'Wang Wu': 85}
print(type(d1), d1)

# Keys in a dictionary cannot be duplicated. If duplicates occur, the later one overwrites the earlier one
d1 = {'Zhang San': 72, 'Li Si': 60, 'Wang Wu': 85, 'Zhang San': 99}
print(d1)

# Define an empty dictionary
d1 = {}
d2 = dict()
print(type(d1), d1)
print(type(d2), d2)

# Keys in a dictionary must be immutable types, but values can be any type
# Plain understanding: Only immutable things can serve as keys
d1 = {'Zhang San': 72, 'Li Si': 60, 'Wang Wu': 85}
d1 = {250: 72, 'Li Si': 60, 'Wang Wu': 85}
d2 = {('Smoking', 'Drinking'): 72, 'Li Si': 60, 'Wang Wu': 85}
print(d1, d2)
# Error example: Using a list as a key is not allowed
# d2 = {['Smoking', 'Drinking']: 72, 'Li Si': 60, 'Wang Wu': 85}  # Error

# Dictionaries can be nested
student_dict = {
    2025001: {'Name': 'Zhang San', 'Age': 18, 'Score': 72, 'Hobbies': ['Smoking', 'Drinking', 'Perming hair']},
    2025002: {'Name': 'Li Si', 'Age': 19, 'Score': 60, 'Hobbies': ['Singing', 'Dancing', 'Playing pool']},
    2025003: {'Name': 'Wang Wu', 'Age': 20, 'Score': 85, 'Hobbies': ['Studying', 'Reading', 'Practicing Tai Chi']}
}
print(student_dict)

80. Dictionaries_CRUD Operations

# Query
from unittest import result

d1 = {'Zhang San': 72, 'Li Si': 60, 'Wang Wu': 85}
# Direct value access, if the key does not exist, an error occurs
result = d1['Zhang San']
print(result)
# result = d1['Ultraman']  # Runtime error
# print(result)
# Safe value access, if the key does not exist, returns a default value (if no default is set, returns None)
result = d1.get('Ultraman')
print(result)  # None
result = d1.get('Ultraman', 'Sorry, key does not exist!')
print(result)  # Sorry, key does not exist!
result = d1.get('Zhang San', 'Sorry, key does not exist!')
print(result)  # 72

# Add
d1 = {'Zhang San': 72, 'Li Si': 60, 'Wang Wu': 85}
d1['Zhao Liu'] = 100
print(d1)

# Modify
d1 = {'Zhang San': 72, 'Li Si': 60, 'Wang Wu': 85}
# The syntax for modification is the same as for addition. If the dictionary has the corresponding key, it's a modification; if not, it's an addition
d1['Zhang San'] = 97
print(d1)

# Batch modification
d1.update({'Li Si': 40, 'Wang Wu': 67})
print(d1)

# Delete
d1 = {'Zhang San': 72, 'Li Si': 60, 'Wang Wu': 85}

# Delete the key-value pair corresponding to the specified key
del d1['Zhang San']
print(d1)

# Delete the key-value pair corresponding to the specified key and return the value associated with that key
result = d1.pop('Zhang San')
print(result)  # 72

# The pop method can set a default value
# The default value ensures that if the key to be deleted does not exist, the program will not error and will return this default value
# result = d1.pop('Ultraman')  # Runtime error
print(d1)
print(result)
result = d1.pop('Ultraman', 'Deletion failed')
print(d1)
print(result)  # Deletion failed
result = d1.pop('Zhang San', 'Deletion failed')
print(d1)
print(result)  # 73

# Clear the dictionary
d1.clear()
print(d1)
Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

饺子不放糖

Keep it up, I'm learning along with you

__sjfzllv___

Let's encourage each other