List 1.

  • List to create

    • ListName = [element 1, Element 2, element n]

    • ListName represents the name of the list, which can be an identifier that conforms to Python naming rules: “element1, Element 2, Element n” represents an unlimited number of elements in the list. And as long as the data type is supported by Python.

    num = [7.14.21.28.35.42.49.56.63]
    verse = ['Since ancient times, autumn is sad and lonely.'.I said autumn is better than spring..'A crane in a clear sky.'.'To the blue sky']
    untitle = ['Python'.28.'Life is short'.'I use Python'['crawlers'.'Automated Operation and Maintenance'.'Cloud computing']]
    python = ['elegant'.'clear'.'simple']
    Copy the code
    • Note: When using lists, it is possible to put different types of data into the same list, but usually we do not do this. Instead, we put only one type of data into a list to improve the readability of the program.

  • Creating an empty list

    emptylist = []
    Copy the code
  • Creating a list of values

    • In Python, numeric lists are common. For example, a list of values can be used to record a student’s score in an exam system, or to record the position of each character in a game, the score of each player, etc. In Python, you can use the list() function to directly convert the result of the loop from the range() function to a list.

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

      • Data represents data that can be converted to a list. It can be a range object, a string, a meta-ancestor, or another iterable type of data.

      list(range(10.20.2)) # [10, 12, 14, 16, 18]
      Copy the code
  • Delete the list

    • You can use the DEL statement to delete a list that has been created and is no longer in use. The syntax is as follows:

    • Del statements are not often used in real development. Python’s own garbage collection mechanism destroys unused lists automatically. So even if we don’t remove it manually, Python will recycle it automatically.

    Team = [' Real Madrid ', 'Roma ',' Liverpool ', 'Bayern '] del teamCopy the code
  • Access list elements

    • In Python, if you want to print out the contents of a list, you can use it directlyprint()Delta function. For example, to create a list named Untitle and print the list, use the following code:
    untitle = ['Python'.28.'Life is short, I use Python'['crawlers'.'Automated Operation and Maintenance'.'Cloud computing']]
    print(untitle) # [' Python, 28, 'life is too short, I use Python, [' crawlers',' automated operations, 'cloud computing']]
    Copy the code
    • You can also get the specified element from the index of the list. For example, to get the element whose index is 2 in the Untitle list.
    print(untitle[2]) # Life is short. I use Python
    Copy the code
  • Traverse the list

    • Traversal of all elements in the list is a common operation, in the traversal process can complete the query, processing and other functions. In daily life, if you want to buy a piece of clothes in a shopping mall, you need to go through the shopping mall to see if there is any clothes you want. The process of shopping in the shopping mall is equivalent to the traversal operation of the list. There are several ways to iterate over a list in Python, and here are two common ones.

      • Use a for loop
      team = ['the rocket'.'the warriors'.Trailblazer.'Sir']
      for item in team:
          print(item) # Rocket Warriors Pioneer Jazz
      Copy the code
      • Use the for loop and enumerate() function

        • Use the for loop and the enumerate() function to output both the index value and the element content
        team = ['the rocket'.'the warriors'.Trailblazer.'Sir']
        for index,item in enumerate(team):
            print(index, item) # 0 rocket
                               # 1 the warriors
                               # 2 Blazers
                               # 3 Sir
        Copy the code
  • Add, modify, and delete list elements

    • Add elements

      • Append () :The append() method of a list object is used to append elements to the end of the list
      phone = ['MOTOROLA'.Nokia.'samsung'.'OPPO']
      phone.append('iPhone')
      print(phone) # [' MOTOROLA ', 'Nokia ',' Samsung ', 'OPPO', 'iPhone']
      Copy the code
      • The extend () :Use to add all elements from one list to another
      oldPhone = ['samsung'.'apple']
      newPhone = ['huawei'.'millet']
      oldPhone.extend(newPhone)
      print(oldPhone)  # [' Samsung ', 'Apple ',' Huawei ', 'Xiaomi ']
      Copy the code
    • Modify the element

      • To modify an element in a list, you simply need to get the element by index and then copy it again.
      phone = ['samsung'.'millet'.'apple'.Nokia]
      phone[-1] = 'huawei'
      print(phone) # [' Samsung ', 'Xiaomi ',' Apple ', 'Huawei ']
      Copy the code
    • Remove elements

      • There are two main cases to delete an element, one is to delete it according to the index, the other is to delete it according to the element value.

        • Delete by index
        verse = ['Beyond the Long Pavilion'.'Along the ancient Road'.The grass is green and the sky is green.]
        del verse[-1]
        print(verse) # [' long Pavilion ', 'ancient Road ']
        Copy the code
        • Delete by element value

          • If you want to remove an element whose position is uncertain, you can remove it based on the element value
          team = ['the rocket'.'the bulls'.Trailblazer.'Sir']
          team.remove('the bulls')
          print(team) # [' Rockets ',' Blazers ',' Jazz ']
          Copy the code
          • Using list objectsremove()Method to delete an element that does not exist, an error is reported. All useremove()Method to determine whether an element exists before deleting it. Of a list objectcount()The method is used to determine the number of occurrences of the specified element.
          team = ['the rocket'.'the bulls'.Trailblazer.'Sir']
          value = 'the bulls'
          if team.remove(value) > 0 :
              team.remove(value)
          print(team) # [' Rockets ', 'Blazers ',' Jazz ']
          Copy the code
  • Perform statistics and calculations on lists

    • Gets the number of occurrences of the specified element

      • Using list objectscount()Method to get the number of occurrences of a specified element in a list
      song = ['The clouds are flying'.'I'm in the Devil's Paradise.'.'Give you a horse'.'Half pot yarn'.'The clouds are flying'.'Meet you'.'You've been waiting so long.']
      num = song.count('The clouds are flying')
      print(num) # 2
      Copy the code
    • Gets the first occurrence of the specified element

      • Using list objectsindex()Method to get the first occurrence (index) of a specified element in a list
      song = ['The clouds are flying'.'I'm in the Devil's Paradise.'.'Give you a horse'.'Half pot yarn'.'The clouds are flying'.'Meet you'.'You've been waiting so long.']
      position = song.index('The clouds are flying')
      print(position)
      Copy the code
    • The sum of the elements in a list of statistics values

      • In Pytnon, the sum() function is provided to count the sum of elements in a list of values

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

          • Iterable: Indicates the list to be counted

          • Start: Sets the initial statistics value. The default value is 0

      grade = [98.99.97.100.100]
      total = sum(grade, 100) 
      print(total) # 594
      Copy the code
  • Sort the list

    • Use the sort() method of the list object

      • Sort (key=None, reverse=False) listname.sort(key=None, reverse=False)

        • Listname: Indicates the list to be sorted

        • Key: Specifies to extract a key from each element for comparison and to receive a comparison return value

        • Reverse: This parameter is optional. If it is True, the data is sorted in descending order. False indicates ascending order, which is the default

        char = ['cat'.'tom'.'Angela'.'pet']
        def length(item) :
            return len(item) Sort each item in descending order by length
        char.sort(key=length, reverse=True) # ['Angela', 'cat', 'tom', 'pet']
        Copy the code
    • Use the built-in sorted() function

      • The sorted() function has the following syntax: sorted(iterable, key=None, reverse=False)

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

        • Key: Specifies to extract a key from each element for comparison and to receive a comparison return value

        • Reverse: This parameter is optional. If it is True, the data is sorted in descending order. False indicates ascending order, which is the default

        char1 = ['cat'.'tom'.'Angela'.'pet']
        def length(item) :
            return len(item) Sort each item in descending order by length
        char2 = sorted(char1, key=length, reverse=Ture)
        print(char2) # ['Angela', 'cat', 'tom', 'pet']
        Copy the code
  • List derivation

    • Generates a list of values in the specified range in the following syntax: list = [Expression for var in range]

      • List: indicates the name of the generated list

      • Expression:

      • Var: loop variable

      • Range: Range objects generated by the range() function

      import random Import the random library
      randomnumber = [random.randint(10.100) for i in range(10)]
      print('Generate random number:', randomnumber) # [78, 84, 21, 60, 74, 50, 65, 15, 94, 90]
      Copy the code
    • Generate a list of specified requirements based on the list. The syntax is as follows: newList = [Expression for var in list]

      • Newlist: indicates the name of the newly generated list

      • Expression: Expression used to evaluate the elements of a new list

      • Var: Variable with the value of each element in the following list

      • List: The original list used to generate a new list

      • For example, define a list of items to record prices, and then apply the list derivation to generate a list of all items with a 50% discount as follows:

      price = [1200.5330.2988.6200.1998.8888]
      sale = [int(i * 0.5) for i in price]
      print(Original price:, price)
      print('50% off the price:', sale)
      Copy the code
    • The syntax is as follows: newList = [Expression for var in list if condition]

      • Newlist: indicates the name of the newly generated list

      • Expression: Expression used to evaluate the elements of a new list

      • Var: Variable with the value of each element in the following list

      • List: The original list used to generate a new list

      • Condition: A condition expression that specifies a filter condition

      • For example, define a list of commodity prices, and then apply the list derivation to generate a list of commodity prices higher than 5000 yuan, the 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('Priced above 5000 :', sale)
      Copy the code