Python

Python list : How to add elements

arage.com@gmail.com

There are various ways to operate Python lists, but in this article, we will specifically elaborate on how to add elements.

How to Add Elements to a List: append()

In Python, you can add a new element to the end of a list using a built-in method called append(). Here’s an example of how to use it:

1fruits = ["apple", "banana", "cherry"]
2fruits.append("dragonfruit")
3print(fruits)
4# Output: ['apple', 'banana', 'cherry', 'dragonfruit']

In this code, the new element “dragonfruit” is added to the end of the list.

How to Add Multiple Elements to a List

When you want to add multiple elements to a list at once, you use a method called extend(). This allows you to add elements from another list or a tuple at once.

1fruits = ["apple", "banana", "cherry"]
2more_fruits = ["dragonfruit", "elderberry", "fig"]
3fruits.extend(more_fruits)
4print(fruits)
5# Output: ['apple', 'banana', 'cherry', 'dragonfruit', 'elderberry', 'fig']

In this example, all elements of another list, more_fruits, are added to the original list, fruits.

How to Insert an Element into a List: insert()

If you want to insert a new element at a specific position in a list, Python provides a method called insert(). The insert() method takes two arguments, the index where you want to insert the new element, and the element you want to insert.

Here is an example of how to use it:

1fruits = ["apple", "banana", "cherry"]
2fruits.insert(1, "avocado")
3print(fruits)
4# Output: ['apple', 'avocado', 'banana', 'cherry']

In this code, the new element “avocado” is inserted at index 1 (the second position). Remember that list indices in Python start at 0.

Also, if you specify an index that is greater than the length of the list, the element is added to the end of the list.

1fruits = ["apple", "banana", "cherry"]
2fruits.insert(10, "avocado")
3print(fruits)
4# Output: ['apple', 'banana', 'cherry', 'avocado']

In this example, because index 10 is greater than the length of the list (which is 3), “avocado” is added to the end of the list.

記事URLをコピーしました