What is a list? How do I use lists?

  • Lists allow you to store groups of information in one place, ranging from just a few elements to millions of elements.

What is a list?

  • A list consists of a series of elements arranged in a particular order.
  • Lists often contain multiple elements, so it’s a good idea to give a list a name that represents a plural number, such as letters, digits, or names.
  • In Python, a list is represented by square brackets ([]) and its elements are separated by commas.
  • Simple examples of lists:
bicycles = ['trek'.'cannondale'.'redline'.'specialized']
print(bicycles)
Copy the code

Access list elements

  • Lists are ordered collections, so to access any element of the list, you simply tell Python the location (index) of that element.
  • From the listbicyclesExtract the first bicycle from:
print(bicycles[0])
Copy the code

The index starts at 0 instead of 1

  • In Python, the index of the first list element is 0, not 1.
  • The following code accessThe index 1The index of 3Bicycle at:
print(bicycles[1])
print(bicycles[3])
Copy the code
  • These codes return to the listThe secondThe fourthElements.
  • Python to accessThe last list elementA special syntax is provided. By putting theThe index is specified as -1To make Python returnThe last list element:
print(bicycles[-1])
Copy the code

Use the values in the list

  • You can use each value in the list just like any other variable.
  • You can use the f string to create a message based on the values in the list:
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
Copy the code

Modify, add, and delete elements

  • Most of the lists you create will bedynamicThis means that once the list is created, elements will be added and deleted as the program runs.

Modifying list elements

  • To modify list elements, specifyA list of namesAnd the list of things to changeThe index, and specify a new value for the element.
  • Suppose you have a list of motorcycles in which the first element ishonda, change its value:
motorcycles = ['honda'.'yamaha'.'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
Copy the code
  • You can change the value of any list element, not just the first one.

Add elements to the list

  • Python provides a variety of ways to add new data to existing lists.
  1. Add an element to the end of a list: The easiest way to add a new element to a list is to append the element to the list.
motorcycles = ['honda'.'yamaha'.'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
Copy the code
  1. Insert elements into a list: useinsert()New elements can be added anywhere in the list. butYou need to specify the index and value of the new element.
motorcycles = ['honda'.'yamaha'.'suzuki']
print(motorcycles)
motorcycles.insert(0.'ducati')
print(motorcycles)
Copy the code
  • methodsinsert()Index 0Add space to, and place the valueducatiI’m going to store it here.

Removes elements from the list

  • You can remove elements from a list by position or value.
  1. usedelStatement delete element: Used if you know the position of the element to be deleted in the listdelStatements.
motorcycles = ['honda'.'yamaha'.'suzuki']
print(motorcycles)
del(motorcycles[0])
print(motorcycles)
Copy the code
  • usedelYou can delete a list element at any location, provided that its index is known.

Once the value is removed from the list using the del statement, you can no longer access it.

  1. Method of usepop()Delete element: methodpop()Delete the listAt the end ofElement, and allow you to continue using it.
  • A list is like a stack, and deleting an element at the end of the list is like popping an element at the top of the stack.
  • Let’s take a look at the listmotorcyclesA motorcycle pops up in:
motorcycles = ['honda'.'yamaha'.'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
Copy the code
  1. Popup an element anywhere in the list: actually, it can be usedpop()To delete the listAny positionSimply specify in parentheses the element to be deletedThe indexCan.
motorcycles = ['honda'.'yamaha'.'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")
Copy the code

If you’re not sure whether to use the del statement or the pop() method, here’s a simple rule: If you want to remove an element from a list and no longer use it in any way, use the del statement. Use the pop() method if you want to continue using an element after it has been deleted.

  1. Delete elements by value: if only the element to be deleted is knownvalue, can be usedremove().
  • Let’s say I want to go from a listmotorcyclesRemove the valueducati:
motorcycles = ['honda'.'yamaha'.'suzuki'.'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
Copy the code
  • useremove()When an element is removed from the list, its value can also be used.

The remove() method removes only the first specified value. If the value to be deleted may appear more than once in the list, you need to use a loop to ensure that each value is removed.

Group list

Method of usesort()Sort the list permanently

cars = ['bmw'.'audi'.'toyota'.'subaru']
cars.sort()
print(cars)
Copy the code
  • methodssort()Permanently changes the order of list elements.
  • You can also arrange list elements in reverse alphabetical order by directing thesort()Method pass parameterreverse=TrueCan.
cars = ['bmw'.'audi'.'toyota'.'subaru']
cars.sort(reverse=True)
print(cars)
Copy the code

Using the functionsorted()Temporarily sort the list

  • To preserve the original order of list elements while rendering them in a specific order, use functionssorted().
  • functionsorted()Allows you to display list elements in a specific order without affecting their original order in the list.
  • Try calling this function on a list of cars:
cars = ['bmw'.'audi'.'toyota'.'subaru']
print("Here is the original list:")
print(cars)
print("Here is the sorted list:")
print(sorted(cars))
print("Here is the original list again:")
print(cars)
Copy the code
  • Call a functionsorted()The order of the list elements remains the same. If you want to display the list in reverse alphabetical order, you can also direct to a functionsorted()Passing parametersreverse=True.

Print the list backwards

  • To reverse the order of list elements, use methodsreverse().
cars = ['bmw'.'audi'.'toyota'.'subaru']
print(cars)
cars.reverse()
print(cars)
Copy the code
  • reverse()Instead of ordering list elements in reverse alphabetical order, you simply reverse the order of list elements.
  • methodsreverse()Permanently changes the order of list elements, but can be restored at any time by calling the list againreverse()Can.

Determine the length of the list

  • Using the functionlen()You can quickly see the length of the list.
cars = ['bmw'.'audi'.'toyota'.'subaru']
print(len(cars))
Copy the code

Avoid indexing errors when using lists

  • An index error means that Python cannot find the element at the specified index.
  • When an index error occurs, try to decrease the specified index by 1, and then run the program again to see if the result is correct.