In Python, you can use lists to save multiple items in a single variable. One of the four built-in data types in Python for storing collections of data is a list; the other three are tuples, sets, and dictionaries, each of which has a unique purpose.
What is a list?
Square brackets are used to build lists. The most powerful tools in Python are lists, since they are not necessarily homogeneous. Data types like integers, strings, and objects can all be found in a list. Since lists are mutable, they can be changed even after they are created.
The ability of Python lists to contain duplicate values is one of its primary features. This allows us to loop through the items of the list and determine the value of each item. If the value must be replaced, we will do so.
In this article, we will learn six ways to replace elements in a list using python programs.
Use For Loop
Python's for loop is used to iterate iterable objects such as strings, tuples, lists, sets, or dictionaries in sequence. So, we will use for loop here which will iterate over the given list and replace the values or elements in the list. For example, we select two elements in the list, such as "coffee" and "tea". Now, we want to replace them with "juice" and "limeade." To accomplish the task, we will use for loop and if condition to replace elements.
algorithm
First define the list.
Use a for loop to create a range that is a list of elements to iterate over.
Use if statement to replace elements.
Print the list in the output.
Example
In the following program, a list of elements is defined. Then, for each element in the list, the if statement checks whether it matches "Coffee" or "Tea".
If so, the element will be replaced with "juice" or "limeade" respectively. Finally, print the new list.
# First define a list of elements list_1 = ['Coffee', 'Sting', 'Maza', 'Tea', 'Tea'] for i in range(len(list_1)): # if statement for replacing elements if list_1[i] == 'Coffee': list_1[i] = 'Fruit juice' # if statement for replacing elements if list_1[i] == 'Tea': list_1[i] = 'Lime soda' print(list_1)
Output
['Fruit juice', 'Sting', 'Maza', 'Lime soda', 'Lime soda']
Use list index
You can use an index to access the entries of a list. The easiest and most straightforward way to replace elements in a list in Python is to use it. Using index 0, we can change the first item in the list.
In the example below, the new value is the value that should replace the previous value in the list, and the index is the index of the item we want to change.
grammar
list_1[index]= Replaced value (Replaced value= new value)
algorithm
First define the list.
Replace the value with the index number.
Print the list in the output.
Example
The following program replaces elements in a list. The initial list includes "TV", "STD", and "WIFI". After printing the complete list, the second element "STD" will be replaced with the value "mobile phone".
# first define a list of elements list_1 = ['Television', 'STD', 'WIFI'] # replacing elements using index list_1[1]= 'Mobile phone' print(list_1)
Output
['Television', 'Mobile phone', 'WIFI']
Using While Loop
To replace the values in the list, we can also use a while loop. The work of the for loop is repeated by the while loop. We define a variable with a value of 0 and first iterate through the list in a while loop. If the value matches the one we wish to change, the old value will be replaced.
algorithm
First define the list.
Define a variable.
Apply while loop.
If the variable value matches the value in the list, it will replace the element.
Print the list in the output.
Example
In the following program, a list containing four elements is created. The while loop iterates through the items in the list, if an item is equal to "VIVO" it will be replaced with "OPPO". Then print the modified list.
# first define a list list_1 = ['REALME', 'REDME', 'APPLE', 'VIVO'] i = 3 while i < len(list_1): # replace VIVO with OPPO from the list if list_1[i] == 'VIVO': list_1[i] = 'OPPO' i += 1 print(list_1)
Output
['REALME', 'REDME', 'APPLE', 'OPPO']
Use list slicing
In Python, you must slice a list to access a specific subset of its elements. One way to do this is using a colon, a simple slicing operator (:). With the help of this operator, you can declare the start and end points of steps and slices. From the original list, list slicing produces a new list.
grammar
list_1 = list_1[: index]+[‘N_V’]+list_1[index+1:] *(N_V= new value)
algorithm
First define the list
The next step is to find the index of the replacement element
Replace elements using list slices.
Print the list in the output.
Example
Here, Python gives us the option to slice the list. Thanks to slicing, we can access some components of the list. Slicing allows us to replace elements within a list. We first find the variable index to be replaced and store it in variable "i".
Then, using list slicing, we replace the item with the new value. If we want to replace "Replication" with "Radiation", we must first determine the index of "Replication", then perform list slicing, take out "Replication" and replace it with "Radiation".
list_1 = ['Heat', 'Replication', 'Induction', 'Conduction', 'Precipitation'] i = list_1.index('Replication') list_1 = list_1[:i]+['Radiation']+list_1[i+1:] print(list_1)
输出
['Heat', 'Radiation', 'Induction', 'Conduction', 'Precipitation']
使用 Lambda 函数
Python Lambda 函数的匿名性质表明它们缺少名称。众所周知,标准 Python 函数是使用 def 关键字定义的。与此类似,Python 使用 lambda 关键字来定义匿名函数。
无论参数数量如何,此函数中都只会计算并返回一个表达式。
Lambda 函数可以用在需要函数对象的任何地方。必须始终牢记 lambda 函数在语法上仅限于单个表达式这一事实。
语法
list_1=list(map(lambda x: x.replace(‘O_V’,’N_V’),list_1))
算法
定义一个列表。
使用 lambda 和 map 函数替换值。
打印列表作为输出。
示例
在这里,为了使用这种方式替换列表中的元素,我们使用 lambda 和 map 函数。 Python 有一个名为 map() 的内置方法,它允许您在不使用循环语句的情况下循环遍历列表。
作为替换值的要求,我们在此处提供了一个表达式。在这里,在 lambda 函数中,我们将“复制”替换为“辐射”。然后使用 list() 函数将地图对象转换为列表。
list_1 = ['Heat', 'Replication', 'Induction', 'Conduction', 'Precipitation'] list_1 = list(map(lambda x: x.replace('Replication', 'Radiation'), list_1)) print(list_1)
输出
['Heat', 'Radiation', 'Induction', 'Conduction', 'Precipitation']
结论
在本文中,我们简要解释了使用 python 语言替换元素的五种不同方法。
The above is the detailed content of Python program: replace elements in a list. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software