In this aritcle you will learn about actions on a Python list. A list is not just defined, it's an interactive object to which you can add and remove items.
A list is just a collection of objects, which can be numbers, strings or other types of objects.
Some example lists:
a = [1,2,3]
b = ["hello","world","moon"]
insert an element into list
There is a previous method of appending an element to the list, which is only the last of the new elements added to the list.For example:
>>> all_users = ["alice","bob"]
>>> all_users.append("aaron")
>>> all_users
['alice', 'bob', 'aaron']
>>>
From this operation, it can be said that list can be changed at any time.
Similar to list.append(x), list.insert (i, x) can also add list elements. It is just that an element can be added anywhere.
list.insert(i, x)
This insert an item at a given position. The first argument is the index of the element at which to insert, so
a.insert(0, x)inserts at the front of the list, anda.insert(len(a), x)is equivalent toa.append(x).
Delete elements in list
The elements in the list can not only be added, but can also be deleted.There are two ways to delete a list element, which are:
list.remove(x)
Remove the first item from the list whose value is x. It is an error if
there is no such item.
list.pop([i])
Remove the item at the given position in the list, and return it. If no
index is specified, a.pop() removes and returns the last item in the list.
>>> all_users = ["alice","bob","aaron"]
>>> all_users.remove('bob')
>>> all_users
['alice', 'aaron']
>>>
Related links:
Top comments (0)