Home >Backend Development >Python Tutorial >Python program: replace elements in a list

Python program: replace elements in a list

WBOY
WBOYforward
2023-08-25 18:48:437226browse

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)

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete