Home > Backend Development > Python Tutorial > Python program to add elements to list

Python program to add elements to list

WBOY
Release: 2023-09-06 08:13:11
forward
1620 people have browsed it

Python program to add elements to list

In this article, we will learn how to add elements to a list. In python, there are multiple ways to add elements to a list using different operators. "Operators" are special symbols for performing arithmetic or logical calculations. The values ​​that an operator operates on are called "operands". There are many types of operators used in python, such as " " for adding elements, "-" for slicing elements, "*" for repeating elements, etc.

Lists in Python

A list is a data structure in Python, which is a variable, ordered sequence of elements. Lists are used to store multiple items in a single variable. Lists consist of four built-in data types in Python that are used to store collections of data. The other three are tuples, sets, and dictionaries.

Example

The following example creates three lists - list1, list2, and list3. List1 contains the numbers 1, 2, 3 and 4; List2 contains the strings "keshav", "mohan" and "govind"; List3 combines elements from both lists and contains a number followed by a string.

list1 = [1,2,3,4]
print (list1)
list2 = ["keshav","mohan","govind"]
print (list2)
list3 = [1,"keshav",2,"mohan"]
print(list3)
Copy after login

Output

[1, 2, 3, 4]
['keshav', 'mohan', 'govind']
[1, 'keshav', 2, 'mohan']
Copy after login

Before learning how to add list elements, we first learn how to create a list. This will provide a quick review of basic concepts.

Create List

We can create a list by placing elements inside square brackets [ ] and separated by commas. Let's learn it through an example.

Example

The following example shows how to create a list. Here we take three names: "alina", "akash" and "arjun".

list= ["alina","akash", "arjun"]
print(list)
Copy after login

Output

Execution of the program given above will produce the following list of names.

['alina', 'akash', 'arjun'] 
Copy after login

Elements in the list

Lists are mutable, which means that the element can be changed, added, and subtracted (sliced).

We use the operator = to change an item or element in a list.

Example

The following examples define names.

names=["ann","yash","maria"]
print(names)
Copy after login

Output

After executing the above program, we get the following output, which prints the elements present in the list as shown below.

['ann', 'yash', 'maria']
Copy after login

Example

HereOperator= is used to change elements. In this example, step 1 shows the list of names as ann, yash, maria, but in step 2 we use the "=" operator to change the last name "maria" to "mike".

names = ["ann","yash","maria"]
print(names)
names [2] = "mike"
print (names)
Copy after login

Output

Executing the above program produces the following output, changing the name "Maria" to "Mike" using the = operator

['ann', 'yash', 'maria']
['ann', 'yash', 'mike']
Copy after login

Add elements to the list

We can use append(), extend(), insert(), concatenation() to add items to the list.

Python allows users to add elements to lists in various ways. The append() method adds an element to the end of the list, while the extend() appends multiple items at once.

Insert() can be used to insert an item at any given index, while concatenation() merges two lists into one. All four methods are useful for adding elements to Python lists.

Use the concatenation operator (" ")

Concatenation is the process in Python of combining two or more strings together. This can be done using the " " operator or using formatting functions such as str.format(), f string and format specifiers. Concatenation allows us to create longer strings by concatenating shorter strings together.

Example

The example given below adds two lists together. The first list, names1, contains the names Ann, Yash, and Maria. The second list, names2, contains the names John, Andrew, and Robin.

names1=["ann","yash","maria"]
names2=["john","andrew","robin"]
print(names1+names2)
Copy after login

Output

['ann', 'yash', 'maria', 'john', 'andrew', 'robin']
Copy after login

Use the Append() method

Append() is a built-in method in Python that is used to add elements to the end of a list. It takes one parameter, which can be any data type, such as an integer, string, or other list.

This method returns nothing; it simply modifies the original list by adding new elements. Append() is a useful way to add items to a list in Python.

Example

This example adds the string "cherry" to a list of fruits named "fruit". Once added, print out the list, which now includes "apple", "mango", "banana", and "cherry".

fruit=["apple", "mango", "banana" ]
a="cherry"
fruit.append(a)
print ("the updated list :",fruit) 
Copy after login

Output

the updated list : ['apple', 'mango', 'banana', 'cherry']
Copy after login

In this program, we have a list of three fruits: ['apple', 'mango', 'banana'], and we want to add the fourth fruit name "cherry" to the last element of the list. Here we use append() as the operator, and the output we get is: ['apple', 'mango', 'banana', 'cherry'].

Use the Extend() method

. Extend() is a function in Python that adds elements from one list to another list. It appends all items in the iterable to the end of the list, thus extending it. It accepts an iterable object as input and extends the list with its individual elements.

When adding items to an existing list, the original order of the items is preserved. This method does not return any value but updates the existing list in memory with the new value.

示例

在此示例中,我们使用 extend() 函数来扩展元素并将其添加到水果列表中,输出为 ['apple', 'mango', '香蕉','c','h','e','r','r','y']

fruit=["apple", "mango", "banana" ]
a="cherry"
fruit.extend(a)
print("the updated list :",fruit)
Copy after login

输出

the updated list : ['apple', 'mango', 'banana', 'c', 'h', 'e', 'r', 'r', 'y']
Copy after login

使用Insert()方法

Insert()是python中的一个函数,用于在指定位置插入元素。它需要两个参数:要插入的元素的索引以及要插入的项目。

这可用于将元素添加到列表或任何其他数据结构(例如元组和字典)中。请务必注意,插入元素会将内存中该元素后面的所有现有元素移动一位。

示例

在下面的示例中,我们有一个由三种水果组成的列表:['apple', 'mango', 'banana'],由于我们想在特定位置添加“orange”,因此我们使用了插入运算符()。通过这个 insert() 运算符,我们可以在任何索引处添加任何元素。

fruits=['apple','banana','cherry']
fruits.insert(1,'orange')
print(fruits)
Copy after login

输出

['apple', 'orange', 'banana', 'cherry']
Copy after login

结论

在这篇文章中,我们简要解释了如何使用Python向列表中添加元素。我们使用了四种不同的方法insert()、concatenation()、append()、extend()。每个函数都有不同的方式来完成任务,即 Concatenation( ) 用于组合两个列表。 Append() 用于在列表末尾添加元素。 extend() 用于添加和扩展列表中添加的元素。 insert() 用于在任意索引处添加元素。

The above is the detailed content of Python program to add elements to list. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template