2020-8-15 Python3 language foundation 2: lists, tuples, dictionaries, sets


— Sequence is the most basic data structure in python

- Data structure refers to the way data is stored in a computer

— Sequences are used to store an ordered set of data, all data has a unique position (index) in the sequence, and the data in the sequence is assigned an index in the order in which it was added

— Classification of sequences:

  • Mutable sequences (elements in the sequence can change)
    • list
  • Immutable sequences (elements in the sequence cannot be changed)
    - string (str)
    - tuple


  • A list is an object in python
  • An object is an area of ​​memory dedicated to storing data
  • The objects we learned before, like numbers, can only hold a single piece of data
  • Multiple ordered data can be stored in the list
  • Lists are objects used to access objects

list creation

# Create a list, use [] to create a list
my_list = []  # created an empty list

# The data stored in the list, we call the element
# You can access multiple elements in a list, or you can specify the elements in the list when you create the list

my_list = [10]  # Create a list with only one element

# When adding multiple elements to a list, separate multiple elements with commas
my_list = [10, 20, 30, 40, 50]  # Create a list with 5 elements

# Any object can be stored in the list
my_list = [10, 'hell0', True, None, [1, 2, 3], print]

# The objects in the list are stored in the list in the order of insertion, the first inserted object is saved to the first position, and the second is saved to the second position
# We can get the elements in the list by index (index)
#   The index is the position of the element in the list, each element in the list has an index
#   The index starts from 0, the first position of the list is 0, the second position is 1, and so on
my_list = [10, 20, 30, 40, 50]

# Get element in list by index
# Syntax: my_list[index]
# print(my_list[0])
# If the index used exceeds the maximum range, an exception will be thrown
# print(my_list[5])  # IndexError: list index out of range

# Get the length of the list, the number of elements in the list
# len() function, through which you can get the length of the list
# The value of the obtained length is the maximum index of the list + 1

Exercise: Create a list, save the names of your five best friends in the list, then index each friend's name separately


# slice
# Slicing means getting a sublist from an existing list
# Create a list. Generally, when creating a list, the name of the variable will be plural.
stus = ['Sun Wukong', 'Pig Bajie', 'monk sand', 'Tang monk', 'Baigujing', 'spider spirit']

# The index of the list can be negative
# If the index of the list is negative, the elements are taken from the back to the front, -1 for the first to last, -2 for the second to last, and so on
# print(stus[-1])

# Get the specified element by slicing
# Syntax: list[start:end]
#   When an element is obtained by cutting edges, the element at the start position will be included, and the element at the end position will not be included
#   When doing slicing operations, a new list is always returned, which will not affect the original list.
#   In fact, the index of the end position and the end position can be omitted without writing
#   If the end position is omitted, it will be intercepted until the end
#   If the start position is omitted, it will be intercepted from the first element
#   If both the start and end positions are omitted, a copy of the list is created

# Syntax: list[start:end:step]
# The step size indicates the interval of each acquisition element, the default value is 1
# The step size cannot be 0 and can be negative
# If it is negative, it will take elements from the back of the list to the front

General operation

# + and *
# + can concatenate two lists into one list
# * You can repeat the list a specified number of times
my_list = [1, 2, 3] + [4, 5, 6]
my_list = [1, 2, 3] * 2
# print(my_list)

# create a list
stus = ['Sun Wukong', 'Pig Bajie', 'monk sand', 'monk sand', 'monk sand', 'Tang monk', 'Baigujing', 'spider spirit']

# in and not in
# in is used to check if the specified element exists in the list
#   Returns True if exists, otherwise returns False
# not in is used to check if the specified element does not exist in the list
#   Returns True if does not exist, otherwise returns False
# print('Sand monk' in stus)
# print('Sand monk' not in stus)

# len() gets the number of elements in the list

# min() gets the smallest value in the list
# max() gets the maximum value in the list
arrs = [1,3,5,2,4,66,11]

# The two methods (method), the method and the function are basically the same, except that the method must be called in the form of object.method()
# A method is actually a function closely related to an object
# s.index() gets the index of the first occurrence of the specified element in the list
# print(stus.index('Sand monk'))
# The second parameter of index() indicates the starting position of the search, and the third parameter indicates the end position of the search
print(stus.index('monk sand', 3, 5))
# If you get an element that is not in the list, an exception will be thrown
# print(stus.index('The Bull Demon')) ValueError: 'The Bull Demon' is not in list

# s.count() counts the number of times the specified element appears in the list
print(stus.count('Sun Wukong'))

modify element

# create a list
stus = ['Sun Wukong', 'Pig Bajie', 'monk sand', 'Tang monk', 'Baigujing', 'spider spirit']

print('before fixing', stus)
# Modify elements in a list
# Modify elements directly by index
stus[0] = 'sunwukong'
# delete element with del
del stus[2]
# print('modified', stus)

stus = ['Sun Wukong', 'Pig Bajie', 'monk sand', 'Tang monk', 'Baigujing', 'spider spirit']

print('before fixing', stus)
# Modify a list by slicing
# Smart use of sequences when assigning values ​​to slices
# stus[0:2] = [123] replace old element with new element
# stus[0:0] = [123] # Insert element at index 0
# When the step size is set, the number of elements in the sequence must be the same as the number of elements in the slice
# stus[::2] = [123,456,789]

# Remove elements by slicing
del stus[0:2]
stus[1:3] = []
print('after modification', stus)

# The above operation only works for mutable sequences
s = 'hello'
# s[1] = 'a' immutable sequence, cannot be modified by index
# Other sequences can be converted to lists by the list() function
s = list(s)

list method

# list method
# create a list
stus = ['Sun Wukong', 'Pig Bajie', 'monk sand', 'Tang monk', 'Baigujing']
print('original list:', stus)

# append()
# Add an element to the end of the list
# stus.append('Bull Demon King')

# insert()
# Inserts a specified element into the specified position of the list
# parameter:
#   1. The position to insert
#   2. The element to be inserted
# stus.insert(2, 'Bull Demon King')

# extend()
# Extend the current sequence with a new sequence
# Requires a sequence as an argument, which will add the elements of the sequence to the current list
# stus.extend(['Bull Demon King', 'Spider Spirit'])

# clear()
# clear sequence
# stus.clear()

# pop()
# Remove and return the removed element based on the index
# result = stus.pop(2) removes the element with index 2
# result = stus.pop() removes the last element
# print('result=', result)

# remove()
# removes the element with the specified value
# stus.remove('Pig Bajie')

# reverse()
# used to list anyway
# stus.reverse()
# print('After modification:', stus)

# sort()
# Used to sort the elements in the list, the default is ascending training
# If you need to sort in descending order, you need to pass a reverse=True as a parameter
my_list = [1,3,2,5,213,23,11,55,23,43]
print('before fixing:', my_list)
print('After modification:', my_list)

iterate over the list

# Traversing a list means taking out all the elements in the list
# Create a list
stus = ['Sun Wukong', 'Pig Bajie', 'monk sand', 'Tang monk', 'Baigujing', 'spider spirit']

# iterate over the list with while
# i = 0
# while i < len(stus) - 1:
#     print(stus[i])
#     i += 1

# for loop
# grammar:
#   for variable in sequence:
#       code block
# The code of the for loop will be executed multiple times, and there are several elements in the sequence will be executed several times
#   Each time it is executed, an element of the sequence is assigned to the variable
#   So we can use variables to get the elements in the list
for i in stus:

EMS exercises

Do the command line version of EMS(Employee Manager System employee management system)

# EMS(Employee Manager System)
# Features:
#   1. Query employees
#       Display all employees in the current system
#   2. Add
#       Add employees to the current system
#   3. Delete
#       Remove the employee from the system
#   4. Exit
#       Exit system

# Displays the welcome message of the system
print('-' * 20, 'Welcome to Employee Management System', '-' * 20)
# Create a list to save the employee's information, and the employee's information is uniformly saved to the list in the form of a string
emps = ['Sun Wukong\t18\t male\t Huaguoshan', 'Pig Bajie\t28\t male\t Gao Lao Zhuang']

# Create an infinite loop
while True:
    # Display the user's options
    print('Please select an action to do:')
    print('\t1.Query employees')
    print('\t2.Add employees')
    print('\t3.delete employee')
    print('\t4.Exit system')
    user_choose = input('please choose[1-4]:')
    print('-' * 62)
    # Do the relevant actions according to the user's choice
    if user_choose == '1':
        # Query employees
        # print header
        print('\t serial number\t Name\t age\t gender\t address')
        # print(emps)
        # Create a variable to represent the employee's serial number
        n = 1
        # Display employee information
        for emp in emps:
            n += 1
    elif user_choose == '2':
        # Add employees
        # Get the information of the employee to be added, name, age, gender, address
        emp_name = input('Please enter the employee's name:')
        emp_age = input('Please enter the employee's age:')
        emp_gender = input('Please enter the gender of the employee:')
        emp_address = input('Please enter the employee's address:')

        # Create employee information
        # Concatenate the four pieces of information into a string and insert into the list
        emp = f'{emp_name}\t{emp_age}\t{emp_gender}\t{emp_address}'
        # show a prompt
        print('The following employees will be added to the system')
        print('-' * 62)
        print('Name\t age\t gender\t address')
        print('-' * 62)
        user_confirm = input('confirm this action[Y/N]:')

        # judge
        if user_confirm == 'y' or user_confirm == 'yes':
            # confirm
            # Show prompt information
            print('Added successfully!')
            # Cancel the operation
            print('Addition cancelled!')

    elif user_choose == '3':
        # Delete employees, delete employees according to the employee's serial number
        # Get the serial number of the employee to delete
        del_num = int(input('Please enter the serial number of the employee to be deleted:'))

        # Determine whether the serial number is valid
        if 0 < del_num <= len(emps):
            # The input is valid, and the index is obtained according to the serial number
            del_i = del_num - 1
            # show a prompt
            print('The following employees will be removed')
            print('-' * 62)
            print('\t serial number\t Name\t age\t gender\t address')
            print('-' * 62)
            user_confirm = input('This operation is irreversible, do you want to confirm?[Y/N]:')
            # judge
            if user_confirm == 'y' or user_confirm == 'yes':
                # remove element
                # Show tips
                print('Employee has been removed!')
                # Operation canceled
                print('Operation cancelled!')
            # wrong input
            print('Your input is incorrect, please try again!')

    elif user_choose == '4':
        # quit
        print('welcome! goodbye!')
        input('Hit enter to exit!')
        print('Your input is incorrect, please try again!')

    # print dividing line
    print('-' * 62)


# range() is a function that can be used to generate a sequence of natural numbers
r = range(5) # generate a sequence like this [0,1,2,3,4]
r = range(0,10,2)
r = range(10,0,-1)
# The function requires three parameters
#   1. Starting position (can be omitted, the default is 0)
#   2. End position
#   3. Step size (can be omitted, the default is 1)

# print(list(r))

# With range() you can create a for loop that executes a specified number of times
# The for() loop is the same as while except for the way it is created.
#   Including else, including break continue can be used in the for loop
#   And the for loop is also simpler to use
# Take the exercise you did with the while loop and do it again with the for loop!
for i in range(30):

# for s in 'hello':
#     print(s)


# tuple
# A tuple is an immutable sequence
# The way it operates is basically the same as the list
# So when you operate on tuples, just treat the tuple as an immutable list.
# Generally, tuples are used when we want the data not to change, and lists are used in other cases

# Create a tuple
# Use () to create tuples
my_tuple = () # created an empty tuple
# print(my_tuple,type(my_tuple)) # <class 'tuple'>

my_tuple = (1,2,3,4,5) # created a tuple of 5 elements
# Tuples are immutable objects, you cannot attempt to reassign elements in a tuple
# my_tuple[3] = 10 TypeError: 'tuple' object does not support item assignment
# print(my_tuple[3])

# Parentheses can be omitted when the tuple is not an empty tuple
# If the tuple is not an empty tuple, it must have at least one in it,
my_tuple = 10,20,30,40
my_tuple = 40,
# print(my_tuple , type(my_tuple))

my_tuple = 10 , 20 , 30 , 40

# Unpacking (destructuring) of tuples
# Unpacking means assigning each element of the tuple to a variable
a,b,c,d = my_tuple

# print("a =",a)
# print("b =",b)
# print("c =",c)
# print("d =",d)

a = 100
b = 300
# print(a , b)

# Interacting the values ​​of a and b, then we can use the unpacking of tuples
a , b = b , a

# print(a , b)
my_tuple = 10 , 20 , 30 , 40

# When unpacking a tuple, the number of variables must match the number of elements in the tuple
# You can also add a * in front of the variable, so that the variable will get all the remaining elements in the tuple
a , b , *c = my_tuple
a , *b , c = my_tuple
*a , b , c = my_tuple
a , b , *c = [1,2,3,4,5,6,7]
a , b , *c = 'hello world'
# Two or more * variables cannot appear at the same time
# *a , *b , c = my_tuple SyntaxError: two starred expressions in assignment
print('a =',a)
print('b =',b)
print('c =',c)

mutable object

  • Three pieces of data are stored in each object:
    id (identification)

  • A list is a mutable object
    a = [1,2,3]

  • a[0] = 10 (change the object)

    • This operation is to modify the value of the object through the variable
    • This operation does not change the object pointed to by the variable
    • When we modify the object, if other variables also point to the object, the modification will also be reflected in other variables
  • a = [4,5,6] (change amount)

    • This operation is reassigning the variable
    • This operation changes the object pointed to by the variable
    • Reassigning a variable does not affect other variables
  • Generally, only when the variable is assigned a value, the variable is modified, and the rest are modified objects.

# # mutable object
# a = [1,2,3]
# print('Before modification:', a , id(a))

# # Modify list by index
# a[0] = 10
# print('After modification:', a , id(a))

# # reassign variable
# a = [4,5,6]
# print('After modification:', a , id(a))

a = [1,2,3]
b = a
# b[0] = 10
b = [10,2,3]
# print("a",a,id(a))
# print("b",b,id(b))

# == !=  is is not
# == != compares objects for equality 
# is is not compares whether the id s of the objects are equal (to compare whether two objects are the same object)

a = [1,2,3]
b = [1,2,3]
print(a == b) # The values ​​of a and b are equal, using == will return True
print(a is b) # a and b are not the same object and have different memory addresses. Using is will return False


Dictionary data A new data structure called mapping

The role of a dictionary is similar to that of a list, and it is a container for storing objects.

The performance of list storage data is good, but the performance of query data is poor

Each element in the dictionary has a unique name, through which the specified element can be quickly found

When querying elements, the efficiency of dictionaries is very fast

Multiple objects can be stored in the dictionary, each object will have a unique name

​ This unique name, we call it the key (key)

​ This object, we call it the value (value)

​ So the dictionary, we also call it a key-value pair (key-value) structure

Each dictionary can have multiple key-value pairs, and each key-value pair is called an item

# dictionary
# Use {} to create a dictionary
d = {} # created an empty dictionary

# Create a dictionary with data
# grammar:
#   {key:value,key:value,key:value}
#   The value of the dictionary can be any object
#   The keys of the dictionary can be any immutable object (int, str, bool, tuple...), but generally we will use str
#       The keys of the dictionary cannot be repeated. If there is a repetition, the latter will be replaced with the former.
# d = {'name':'Sun Wukong' , 'age':18 , 'gender':'male' , 'name':'sunwukong'}
d = {
'name':'Sun Wukong' ,
'age':18 ,
'gender':'male' ,

# print(d , type(d))

# Need to get the value according to the key
# print(d['name'],d['age'],d['gender'])

# If a key that does not exist in the dictionary is used, an error will be reported
# print(d['hello']) KeyError: 'hello'

Posted by andy666 on Sun, 22 May 2022 21:18:30 +0300