10. Python list

10. Python list

1. List

  • List creation

    • syntax:
      listName = [element 1, element 2, element n]

    • among them,

      listName
      Indicates the name of the list, which can be an identifier that conforms to the Python naming rules: "element1, element 2, element n" represents the elements in the list, and the number is unlimited.
      And as long as it is a data type supported by Python.

    num = [ 7 , 14 , 21 , 28 , 35 , 42 , 49 , 56 , 63 ] verse = [ 'Since ancient times, autumn is sad and lonely' , 'I say autumn is better than spring' , 'a crane in a clear sky and a row of clouds' , 'there will be poetry and love to the blue sky' ] untitle = [ 'Python' , 28 , 'Life is short' , 'I use Python' , [ 'Crawler' , 'Automated operation and maintenance' , 'Cloud computing' ]] Python = [ 'elegant' , 'clear' , 'simple' ] duplicated code
    • Description:
      When using a list, although different types of data can be put into the same list, in general, we don t do this. Instead, we put only one type of data in a list, which can improve the performance of the program. readability.

  • Create empty list

    emptylist = [] Copy code
  • Create a list of values

    • In Python, numeric lists are very common. For example, a list of values can be used to record student performance in the examination system, or record the position of each character in the game, and the score of each player. In Python, you can use

      list()
      Function directly
      range()
      The result of the function loop is converted into a list.

      • The basic syntax of the list() function is as follows: list(data)

      • data represents the data that can be converted to a list, and its type can be

        Range objects, strings, primitive ancestors, or other iterable types of data.

      list ( range ( 10 , 20 , 2 )) # [10, 12, 14, 16, 18] copy the code
  • Delete list

    • For lists that have been created, you can use them when they are no longer in use

      del
      Statement to delete it. The syntax format is as follows:

    • del
      Statements are not commonly used in actual development. Because Python's built-in garbage collection mechanism will automatically destroy unused lists. So even if we don't delete it manually, Python will automatically recycle it.

    team = ['Real Madrid','Rome','Liverpool','Bayern'] del team Copy code
  • Access list element

    • In Python, if you want to output the contents of the list more easily, you can use it directly
      print()
      Function. For example, to create a list named untitle and print the list, you can use the following code:
    untitle = [ 'Python' , 28 , 'Life is short, I use Python' , [ 'Crawler' , 'Automated operation and maintenance' , 'Cloud computing' ]] print (untitle) # ['Python', 28,'Life Too short, I use Python', ['crawler','automated operation and maintenance','cloud computing']] copy the code
    • The specified element can also be obtained by the index of the list. For example, to get the element whose index is 2 in the untitle list.
    print (untitle[ 2 ]) # Life is too short, I use Python to copy the code
  • Traverse the list

    • Traversing all elements in the list is a commonly used operation, and functions such as query and processing can be completed during the traversal process. In life, if you want to go to the mall to buy a piece of clothing, you need to go around in the mall to see if you have the clothes you want. The process of visiting the mall is equivalent to the traversal operation of the list. There are many ways to traverse a list in Python. Here are two common methods.

      • Use for loop to achieve
      Team = [ 'Rocket' , 'warrior' , 'pioneer' , 'Jazz' ] for Item in Team: Print (Item) # warrior rocket pioneer Sir duplicated code
      • Use for loop and enumerate() function to achieve

        • Use for loop and enumerate() function to output index value and element content at the same time
        team = [ 'Rocket' , 'Warrior' , 'Pathfinder' , 'Jazz' ] for index,item in enumerate (team): print (index, item) # 0 Rocket # 1 Warrior # 2 Trailblazer # 3 Jazz copy Code
  • Add, modify and delete list elements

    • Add element

      • append():
        The append() method of the list object is used to append elements to the end of the list
      phone = [ 'Motorola' , 'Nokia' , 'Samsung' , 'OPPO' ] phone.append ( 'the iPhone' ) Print (Phone) # [ 'Motorola', 'Nokia', 'Samsung', 'OPPO', 'iPhone '] Copy the code
      • extend():
        Used to add all elements in one list to another list
      oldPhone = [ 'Samsung' , 'Apple' ] newPhone = [ 'Huawei' , 'Xiaomi' ] oldPhone.extend(newPhone) Print (oldPhone) # [ 'Samsung', 'apple', 'Huawei', 'millet'] Copy the code
    • Modify elements

      • To modify an element in the list, you only need to obtain the element by index, and then copy it again.
      phone = [ 'Samsung' , 'Xiaomi' , 'Apple' , 'Nokia' ] phone[- 1 ] = 'Huawei' print (phone) # ['Samsung','Xiaomi','Apple','Huawei'] Copy code
    • Delete element

      • There are two main situations for deleting elements, one is to delete based on index, and the other is to delete based on element value.

        • Delete according to index
        = Verse [ 'outer pavilion' , 'trail edge' , 'green lawn' ] del Verse [- . 1 ] Print (Verse) # [ 'outer pavilion', 'trail edge'] duplicated code
        • Delete based on element value

          • If you want to delete an element whose position is uncertain, you can delete it according to the element value
          team = [ 'Rocket' , 'Bull' , 'Pathfinder' , 'Jazz' ] team.remove ( 'Chicago' ) Print (Team) # [ 'Rocket', 'pioneer', 'Jazz'] duplicated code
          • Use list objects
            remove()
            When the method deletes an element, if the specified element does not exist, an error will be reported. All use
            remove()
            Before deleting an element, it is best to determine whether the element exists. List object
            count()
            The method is used to determine the number of occurrences of the specified element.
          team = [ 'Rocket' , 'Bull' , 'Pathfinder' , 'Jazz' ] value = 'Bull' if team.remove(value)> 0 : team.remove(value) Print (Team) # [ 'Rocket', 'pioneer', 'Jazz'] duplicated code
  • Statistics and calculations on the list

    • Get the number of occurrences of the specified element

      • Using list objects
        count()
        Method can get the number of occurrences of the specified element in the list
      song = [ 'The clouds are flying' , 'I'm punishing the immortal in a happy stream' , 'Send you a horse' , 'Half a pot of yarn' , 'The clouds are flying' , 'Meeting you' , 'Waiting for you to wait so long' ] song.count = NUM ( 'Flying Cloud' ) Print (NUM) # 2 duplicated code
    • Get the index of the first occurrence of the specified element

      • Using list objects
        index()
        The method can get the position (i.e. index) where the specified element first appears in the list
      song = [ 'The clouds are flying' , 'I'm punishing the immortal in a happy stream' , 'Send you a horse' , 'Half a pot of yarn' , 'The clouds are flying' , 'Meeting you' , 'Waiting for you to wait so long' ] = song.index position ( 'Flying Cloud' ) Print (position) copying the code
    • The elements of the list of statistical values and

      • In Pytnon, it provides

        sum()
        The function is used to count the sum of each element in the list of values

        • The syntax format is as follows:
          sum(iterable[,start])

          • iterable:
            Indicates the list to be counted

          • start:
            Set the initial statistical value, optional, the default value is 0

      grade = [ 98 , 99 , 97 , 100 , 100 ] = Total SUM (Grade, 100 ) Print (Total) # 594 copy the code
  • Sort the list

    • Using list objects

      sort()
      method

      • The elements of the sorted list will change
        List object
        sort()
        The method syntax format is as follows: listname.sort(key=None, reverse=False)

        • listname:
          Indicates the list to be sorted

        • key:
          Indicates that a key for comparison is extracted from each element, and a comparison return value is received

        • reverse:
          Optional parameters, for
          True
          They are sorted in descending order.
          False
          Sort in ascending order, the default is ascending sort

        char = [ 'cat' , 'tom' , 'Angela' , 'pet' ] def length ( item ): return len (item) # Sort according to the length of each item in descending order char.sort(key=length, reverse= true ) # [ 'Angela', 'CAT', 'Tom', 'PET'] duplicated code
    • Use the built-in

      sorted()
      Function implementation

      • After using this function to sort, the elements of the original list remain unchanged
        sorted()
        The syntax format of the function is as follows: sorted(iterable, key=None, reverse=False)

        • iterable:
          Indicates the name of the list to be sorted

        • key:
          Indicates that a key for comparison is extracted from each element, and a comparison return value is received

        • reverse:
          Optional parameters, for
          True
          They are sorted in descending order.
          False
          Sort in ascending order, the default is ascending sort

        char1 = [ 'cat' , 'tom' , 'Angela' , 'pet' ] def length ( item ): return len (item) # Sort according to the length of each item in descending order char2 = sorted (char1, key=length, Ture = Reverse) Print (char2) # [ 'Angela', 'CAT', 'Tom', 'PET'] duplicated code
  • List comprehension

    • Generate a list of values in the specified range, the syntax format is as follows:

      list = [Expression for var in range]

      • list:
        Indicates the name of the generated list

      • Expression:
        expression

      • var:
        Loop variable

      • range:
        The range object generated by the range() function

      import random # Import random standard library randomnumber = [random.randint( 10 , 100 ) for i in range ( 10 )] print ( 'The random number generated is:' , randomnumber) # [78, 84, 21, 60, 74 , 50, 65, 15, 94, 90] copy the code
    • According to the list to generate a list of specified requirements, the syntax format is as follows:

      newList = [Expression for var in list]

      • newlist:
        Indicates the name of the newly generated list

      • Expression:
        Expression used to calculate the elements of the new list

      • var:
        Variable, the value is the value of each element in the following list

      • list:
        The original list used to generate the new list

      • E.g:
        Define a list that records product prices, and then apply the list comprehension to generate a list that discounts all product prices by 50%. The specific code is as follows:

      price = [ 1200 , 5330 , 2988 , 6200 , 1998 , 8888 ] = Sale [ int (I * 0.5 ) for I in . price] Print ( 'original price:' ,. price) Print ( 'play half price:' , Sale) copy the code
    • Select eligible elements from the list to form a new list, the syntax format is as follows:

      newlist = [Expression for var in list if condition]

      • newlist:
        Indicates the name of the newly generated list

      • Expression:
        Expression used to calculate the elements of the new list

      • var:
        Variable, the value is the value of each element of the following list

      • list:
        The original list used to generate the new list

      • condition:
        Conditional expression, used to specify filter conditions

      • E.g:
        Define a list of product prices, and then apply the list comprehension to generate a list with product prices higher than 5000 yuan. The specific code is as follows:

      price = [ 1200 , 5330 , 2988 , 6200 , 1998 , 8888 ] = Sale [X for X in . price IF X> 5000 ] Print ( 'original list:' ,. price) Print ( 'price is higher than 5000:' , Sale) copy the code