Home  >  Article  >  Backend Development  >  How to add elements to an array in python

How to add elements to an array in python

下次还敢
下次还敢Original
2024-05-05 20:21:31550browse

In Python, there are four ways to add elements to a list: use the append() method to append to the end; use the extend() method to add elements of another iterable object; use the insert() method to add elements to the list. Insert at specified position; uses index assignment (but will throw an exception if index is out of range).

How to add elements to an array in python

How to add elements to a Python array

In Python, an array is called a list. Adding elements to the list is very simple, there are several methods:

1. append() method

append() method adds elements to the end of the list. The syntax is as follows:

<code class="python">list.append(element)</code>

For example:

<code class="python">my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 输出:[1, 2, 3, 4]</code>

2. extend() method

extend() method extends another list or tuple The element is added to the end of the original list. The syntax is as follows:

<code class="python">list.extend(iterable)</code>

where iterable can be a list, tuple or other iterable object. For example:

<code class="python">my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list)  # 输出:[1, 2, 3, 4, 5, 6]</code>

3. insert() method

insert() method adds an element to the specified position in the list. The syntax is as follows:

<code class="python">list.insert(index, element)</code>

where index represents the position where the element is to be inserted. For example:

<code class="python">my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)  # 输出:[1, 4, 2, 3]</code>

4. Index assignment

Index assignment can also be used to add elements to a list, but if the index exceeds the range of the list, an IndexError exception will be raised. The syntax is as follows:

<code class="python">list[index] = element</code>

For example:

<code class="python">my_list = [1, 2, 3]
my_list[3] = 4
print(my_list)  # 输出:[1, 2, 3, 4]</code>

The above is the detailed content of How to add elements to an array in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn