📜  Python|返回元素插入的新列表

📅  最后修改于: 2022-05-13 01:54:33.193000             🧑  作者: Mango

Python|返回元素插入的新列表

通常的 append 方法在原始序列中添加新元素并且不返回任何值。但有时我们每次向列表中添加新元素时都需要一个新列表。这种问题在Web开发中很常见。让我们讨论可以执行此任务的某些方式。

方法 #1:使用 +运算符
如果我们制作一个单元素列表并将原始列表与这个新制作的单元素列表连接起来,则可以执行此任务。

# Python3 code to demonstrate 
# returning new list on element insertion
# using + operator
  
# initializing list
test_list = [5, 6, 2, 3, 9]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# element to add 
K = 10
  
# using + operator
# returning new list on element insertion
res = test_list + [K]
  
# printing result 
print ("The newly returned added list : " +  str(res))

输出 :

The original list is : [5, 6, 2, 3, 9]
The newly returned added list : [5, 6, 2, 3, 9, 10]


方法 #2:使用 *运算符
使用 *运算符可以使用类似的任务,其中我们使用 *运算符获取所有元素,并添加新元素以输出新列表。

# Python3 code to demonstrate 
# returning new list on element insertion
# using * operator
  
# initializing list
test_list = [5, 6, 2, 3, 9]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# element to add 
K = 10
  
# using * operator
# returning new list on element insertion
res = [*test_list, K]
  
# printing result 
print ("The newly returned added list : " +  str(res))

输出 :

The original list is : [5, 6, 2, 3, 9]
The newly returned added list : [5, 6, 2, 3, 9, 10]