Table of Contents
What is a list?
Use For Loop
algorithm
Example
Output
Use list index
grammar
Using While Loop
Use list slicing
输出
使用 Lambda 函数
语法
算法
示例
结论
Home Backend Development Python Tutorial Python program: replace elements in a list

Python program: replace elements in a list

Aug 25, 2023 pm 06:48 PM
list element replace

Python program: replace elements in a list

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)
Copy after login

Output

['Fruit juice', 'Sting', 'Maza', 'Lime soda', 'Lime soda']
Copy after login

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)
Copy after login

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)
Copy after login

Output

['Television', 'Mobile phone', 'WIFI']
Copy after login

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)
Copy after login

Output

['REALME', 'REDME', 'APPLE', 'OPPO']
Copy after login

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)
Copy after login

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)
Copy after login

输出

['Heat', 'Radiation', 'Induction', 'Conduction', 'Precipitation']
Copy after login
Copy after login

使用 Lambda 函数

Python Lambda 函数的匿名性质表明它们缺少名称。众所周知,标准 Python 函数是使用 def 关键字定义的。与此类似,Python 使用 lambda 关键字来定义匿名函数。

无论参数数量如何,此函数中都只会计算并返回一个表达式。

Lambda 函数可以用在需要函数对象的任何地方。必须始终牢记 lambda 函数在语法上仅限于单个表达式这一事实。

语法

list_1=list(map(lambda x: x.replace(‘O_V’,’N_V’),list_1))
Copy after login

算法

  • 定义一个列表。

  • 使用 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)
Copy after login

输出

['Heat', 'Radiation', 'Induction', 'Conduction', 'Precipitation']
Copy after login
Copy after login

结论

在本文中,我们简要解释了使用 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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a grocery list: Use the Reminders app for iPhone How to create a grocery list: Use the Reminders app for iPhone Dec 01, 2023 pm 03:37 PM

In iOS 17, Apple added a handy little list feature to the Reminders app to help you when you're out shopping for groceries. Read on to learn how to use it and shorten your trip to the store. When you create a list using the new "Grocery" list type (named "Shopping" outside the US), you can enter a variety of food and groceries and have them automatically organized by category. This organization makes it easier to find what you need at the grocery store or while out shopping. Category types available in alerts include Produce, Bread & Cereals, Frozen Foods, Snacks & Candy, Meat, Dairy, Eggs & Cheese, Baked Goods, Baked Goods, Household Products, Personal Care & Wellness, and Wine, Beer & Spirits . The following is created in iOS17

Master PyCharm replacement shortcut keys in 5 minutes and easily increase your programming speed! Master PyCharm replacement shortcut keys in 5 minutes and easily increase your programming speed! Feb 22, 2024 am 10:57 AM

PyCharm is a commonly used Python integrated development environment with rich functions and shortcut keys that can help developers improve programming efficiency. In the daily programming process, mastering PyCharm's shortcut key replacement skills can help developers complete tasks more quickly. This article will introduce you to some commonly used replacement shortcut keys in PyCharm to help you easily improve your programming speed. 1.Ctrl+R replacement In PyCharm, you can use the Ctrl+R shortcut key to perform replacement operations.

Replace the class name of an element using jQuery Replace the class name of an element using jQuery Feb 24, 2024 pm 11:03 PM

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

Unable to display win7 wireless network list Unable to display win7 wireless network list Dec 22, 2023 am 08:07 AM

In order to facilitate many people's mobile work, many notebooks are equipped with wireless network functions, but some people's computers cannot display the WiFi list. Now I will bring you how to deal with this problem under win7 system. Let's take a look. Bar. The wireless network list cannot be displayed in win7 1. Right-click the network icon in the lower right corner of your computer, select "Open Network and Sharing Center", open it and then click "Change Adapter Settings" on the left 2. After opening, right-click the mouse to select the wireless network adapter, and select "Diagnosis" 3. Wait for diagnosis. If the system diagnoses a problem, fix it. 4. After the repair is completed, you can see the WiFi list.

CSS transformation: how to achieve the rotation effect of elements CSS transformation: how to achieve the rotation effect of elements Nov 21, 2023 pm 06:36 PM

CSS transformation: How to achieve the rotation effect of elements requires specific code examples. In web design, animation effects are one of the important ways to improve user experience and attract user attention, and rotation animation is one of the more classic ones. In CSS, you can use the "transform" attribute to achieve various deformation effects of elements, including rotation. This article will introduce in detail how to use CSS "transform" to achieve the rotation effect of elements, and provide specific code examples. 1. How to use CSS’s “transf

CSS transition effect: how to achieve the sliding effect of elements CSS transition effect: how to achieve the sliding effect of elements Nov 21, 2023 pm 01:16 PM

CSS transition effect: How to achieve the sliding effect of elements Introduction: In web design, the dynamic effect of elements can improve the user experience, among which the sliding effect is a common and popular transition effect. Through the transition property of CSS, we can easily achieve the sliding animation effect of elements. This article will introduce how to use CSS transition properties to achieve the sliding effect of elements, and provide specific code examples to help readers better understand and apply. 1. Introduction to CSS transition attribute transition CSS transition attribute tra

PyCharm replaces shortcut keys to make programming more convenient! PyCharm replaces shortcut keys to make programming more convenient! Feb 21, 2024 pm 12:03 PM

PyCharm is an integrated development environment popular among programmers. It provides powerful functions and tools to make programming more efficient and convenient. In PyCharm, reasonable setting and replacement of shortcut keys is one of the keys to improving programming efficiency. This article will introduce how to replace shortcut keys in PyCharm to make programming more convenient. 1. Why should we replace shortcut keys? In PyCharm, shortcut keys can help programmers quickly complete various operations and improve programming efficiency. However, everyone has different habits, and some people may

See all articles