List methods
In this section, we will discuss list methods, one by one, with examples.
Let's make an empty list and add values one by one:
Avengers = []
In order to add a value to the list, we will use the append ()
method. You will see this method most of the time.
append ()
The syntax for the append ()
method is given as follows:
list.append ()
The method adds a value at the end of the list. Let's see the following example:
>>> Avengers = [] >>> Avengers.append("Captain-America") >>> Avengers.append("Iron-man") >>> Avengers ['Captain-America', 'Iron-man'] >>>
You can see that we have added two members to the list.
Consider a situation where you want to add a list to an existing list. For example, we have two lists of our heroes:
Avengers1 = ['hulk', 'iron-man', 'Captain-America', 'Thor'] Avengers2 = ["Vision","sam"]
We want to add the Avengers2
list to the Avengers1
list. If you are thinking about the +
operator, you might be right to some extent...