The list of

1. What is a list

  • A list consists of a series of elements arranged in a particular order
  • You can add anything to the list that doesn’t have any relationship
  • Lists are usually given a name that represents a complex number (letters, digits, names)
  • In Python, square brackets are used[]Represents a list and uses.Separate the elements
bicycles = ['trek'.'cannondale'.'redline'.'specialized']
print(bicycles)  # Python will print an internal representation of the list, including square brackets
Copy the code

2. Access list elements

  • A list is an ordered collection, so to access any element of the list, simply change the location of that element (The index) tell Python. Format:List name [index]
  • Indexing starts at 0 instead of 1, to avoid indexing errors
bicycles = ['trek'.'cannondale'.'redline'.'specialized']
print(bicycles[0])  When you request a list element, Python returns only that element, not the square brackets
print(bicycles[2].title())  You can call the string method on any list element
print(bicycles[-1].upper())  # Return the last list element by specifying the index -1, and so on
Copy the code

3. Modify, add and delete elements

Modifying list elements

motorcycles = ['honda'.'yamaha'.'suzuki']
print(motorcycles)

motorcycles[0] = 'ducati'  You can specify the name of the list and the index of the element to be modified, and then specify the new value of the element
print(motorcycles)
Copy the code

Add elements to the list

  • The easiest way to add a new element to a list is to attach it to the list

Append D

motorcycles = ['honda'.'yamaha'.'suzuki']
motorcycles.append('ducati')  The # append() method adds the element 'ducati' to the end of the list
print(motorcycles)
Copy the code
  • To control users, you first create an empty list to store user input, and then append each new value provided by the user to the list
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')

print(motorcycles)
Copy the code

Inserts elements into the list

  • useMethods the insert ()New elements can be added anywhere in the list, and the index and value of the new element need to be specified
motorcycles = ['honda'.'yamaha'.'suzuki']

motorcycles.insert(0.'ducati')  The # insert() method adds space at index 0 and stores the value 'ducati' there
print(motorcycles)
Copy the code

Removes elements from the list

Delete elements using the DEL statement

  • If you know the index of the element to be deletedDel statement. Format:Del list name [index]
motorcycles = ['honda'.'yamaha'.'suzuki']
del motorcycles[1]
print(motorcycles)
Copy the code

Remove elements using the pop() method

  • Methods the pop ()Remove the element at the end of the list and allow you to continue using it
  • The termThe pop-upFrom the analogy that a list is like a stack, and removing the element at the end of the list is like popping the element at the top of the stack

Pop v. Go quickly

motorcycles = ['honda'.'yamaha'.'suzuki']
popped_motorcycle = motorcycles.pop()  Pop the end of the list element and assign its value to the variable popped_motorcycle
print(motorcycles)
print(popped_motorcycle)
Copy the code

  • Actually, yespop()To delete an element anywhere in the list, simply specify the index of the element to be deleted in parentheses
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")
Copy the code

pop() or del ?

  • If you want to remove an element from the list and no longer use it in any way, use itDel statement
  • If you want to be able to use an element after it has been deleted, use itMethods the pop ()

Use the remove() method to remove elements based on their values

  • If you do not know the location of the element to be removed from the list and only know the value of the element, you can use theMethods the remove ()
motorcycles = ['honda'.'yamaha'.'suzuki'.'ducati']
motorcycles.remove('ducati')  # remove() removes the element with the value 'ducati'
print(motorcycles)
Copy the code
  • useMethods the remove ()When you remove an element from the list, you can continue to use its value
motorcycles = ['honda'.'yamaha'.'suzuki'.'ducati']
too_expensive = 'ducati'
motorcycles.remove(too_expensive)  # remove() removes the element with the value 'ducati'
print(motorcycles)
print(f"\nA {too_expensive.title()} is too expensive for me")
Copy the code
  • Methods the remove ()Only the first specified value is deleted, and if the value to be deleted occurs more than once, you need to use a loop to ensure that each value is deleted

4. Organize lists

Use the method sort() to sort the list permanently

cars1 = ['bmw'.'audi'.'toyota'.'subaru']
cars2 = ['bmw'.'audi'.'toyota'.'subaru']
cars1.sort()  The # sort() method permanently changes the order of list elements, defaulting to alphabetical order for strings
cars2.sort(reverse=True)  # Pass the parameter reverse=True to sort() to sort the list elements in reverse alphabetical order
print(cars1)
print(cars2)
Copy the code

Use the function sorted() to temporarily sort a list

  • To preserve the original order of the list while rendering them in a specific order, use theFunction sorted ()
cars = ['bmw'.'audi'.'toyota'.'subaru']
print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars, reverse=True))

print("\nHere is the original list again:")
print(cars)
Copy the code

Print the list backwards

  • Methods reverse ()Reverses the order of list elements, regardless of alphabetical order
  • Methods reverse ()Permanently changes the order of list elements. The restore order needs to be called againreverse()
cars = ['bmw'.'audi'.'toyota'.'subaru']
cars.reverse()  The # reverse() method reverses the order of list elements
print(cars)
Copy the code

Determine the length of the list

  • useFunction len ()You can quickly see the length of the list
  • Python counts list elements from 1
cars = ['bmw'.'audi'.'toyota'.'subaru']
print(len(cars))
Copy the code

5. Walk through the list

  • Using a for loop avoids a lot of repetitive code
  • You can do anything on each element in the for loop
  • Choosing meaningful names for individual list elements is helpful, for examplefor item * in list_of_items:
  • Python determines the relationship between a line of code and the previous line based on indentation, and is careful to avoid indentation errors
magicians = ['alice'.'david'.'carolina']
for magician in magicians:  # Define the for loop
    print(f"{magician.title()}, that was a great trick!")

print("Thank you, everyone.")  # After the for loop, any code that does not indent is executed only once
Copy the code

6. Create a value list

Use the function range()

  • Function of the range ()Let Python count from the first specified value and stop when the second specified value is reached
for value in range(1.5) :When # range() specifies a parameter, it starts at 0
    print(value)  Pay attention to bad behavior
Copy the code

Use range() to create a list of numbers

  • useFunction list ()willrange()Is converted directly to the list
numbers = list(range(1.6))  # take range() as argument to list(), the output will be a list of numbers
print(numbers)
Copy the code
  • useFunction of the range (), you can also specify the step size by specifying a third parameter
even_numbers = list(range(2.11.2))  # range() starts at 2 and increments by 2 until the final value is reached or exceeded
print(even_numbers)
Copy the code

Perform a simple statistical calculation on a list of numbers

digits = [1.2.3.4.5.6.7.8.9.0]
print(min(digits))  The function min() returns the minimum value of the list of numbers
print(max(digits))  The function Max () returns the maximum value of the list of numbers
print(sum(digits))  # The function sum() returns the sum of a list of numbers
Copy the code

List of analytical

  • List parsing merges the for loop and the code that creates the new element of the column into a single line, and appends the new element automatically
  • Format:List_of_items = [list_of_items]
  • Notice that there is no colon at the end of the for statement
squares = [value**2 for value in range(1.11)]  Supply 1 to 10 to the expression value**2
print(squares)
Copy the code

7. Use part of a list

slice

  • To create a slice, specify the first element and the index of the last element to be used
  • With the functionrange()Again, Python stops at the element before the second index
players = ['charles'.'martina'.'michael'.'florence'.'eli']
print(players[0:3])  Print the first, second, and third player names
print(players[:4])  # If the first index is not specified, the list automatically starts at the beginning
print(players[-3:)If no second index is specified, the list ends automatically
Copy the code

Traversal section

  • If you want to iterate over part of a list, you can use slicing in the for loop
players = ['charles'.'martina'.'michael'.'florence'.'eli']

print("Here are the first three players: ")
for player in players[:3] :print(player.title())
Copy the code

Copy the list

  • Start by creating a slice that contains the entire list, a copy of the list. And then we assign
my_foods = ['pizza'.'falafel'.'carrot cake']
friend_foods = my_foods[:]
print(friend_foods)
Copy the code
  • If you do not use slice assignment directly:list_A = list_BYou actually associate the new variable list_A with the list already associated with list_B. So these two variables point to the same list, and when you do something on one list, the other one changes

tuples

  • Python calls values that cannot be modified immutable, and immutable lists are called tuples
  • Tuples are simpler data structures than lists. You can use tuples if you want to store a set of values that remain constant throughout the life of the program
dimensions = (200.50)  # use parentheses to identify tuples
dimensions = (240.60)  It is legal to reassign a tuple variable, illegal to change the value of a single tuple element
Copy the code

All the code in the article can be compiled and run successfully by test and can be copied directly. Code with obvious results or simple conclusions does not show run results. Please feel free to contact us if you have any questions