Getting Started with Python 3

List: a perverted strong array

Today we are going to talk about one of the most basic data structures in python, which is a bit similar to the concept of arrays in C. The difference is that the types of elements contained in the list are not unique. You can put various types of things into the same list as follows :


We can see that python's lists are really powerful, and even lists can be added to them. The powerful capacity is only the tip of the iceberg of python lists. There are many ways to use lists in python. We can use dir(list) to check these methods first.


Do not panic when you see so many methods

"Increase" operations include: append(), extend(), insert(). We will introduce them one by one.

append usage:


append() as shown above can add an element to the end of the list, we just need to add .append (content to be added) after our list and enter the content to be added.

extend() usage:

The function of extend is a bit similar to append, but the difference is that append adds objects, while extend adds elements. I don't understand. Let's take an example:



Can you see the difference? Yes, when we call append, the content he adds will only be regarded as an object, the queue length will only increase by one, and extend will put each element into the original list.

Finally, we call this insert() as its name suggests. Its function is to insert elements in the list. It will not be silly to only add elements at the end of the list.


insert() method syntax:

list.insert(index, obj)

parameter

  • index -- The index position (0-based) at which the object obj needs to be inserted.

  • obj – The object to insert into the list.
  • Next, let's talk about how to delete, delete includes the following methods: clear(), remove(), pop()
  • Let's talk about the clear() method first

  • clear() can be regarded as a nuclear weapon-level deletion, delete all elements at one time, remember to use it with caution.
  • Then our remove() method is much gentler than clear, it will only delete the specified element as shown in the figure:

  • The last one is to delete POP(). Students who have studied assembly may know that POP is used to pop the stack. Here, when we call POP, the effect is similar to popping the stack, which will delete the last element.

  • We can see that he successfully removed the last element of the list.
  • Regarding the "addition" and "deletion" of the linked list, let's talk about the next "change" and "check" in the next lesson.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326568769&siteId=291194637