Python | Devolver nueva lista en la inserción de elementos

El método de adición habitual agrega el nuevo elemento en la secuencia original y no devuelve ningún valor. Pero a veces necesitamos tener una nueva lista cada vez que agregamos un nuevo elemento a la lista. Este tipo de problema es común en el desarrollo web. Analicemos ciertas formas en que se puede realizar esta tarea.

Método #1: Usar el operador +
Esta tarea se puede realizar si creamos una lista de un solo elemento y concatenamos la lista original con esta lista de un solo elemento recién creada.

# 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))

Producción :

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

 
Método #2: Usar el operador *
Se puede usar un tipo de tarea similar usando el operador * en el que usamos el operador * para tomar todos los elementos y también agregar el nuevo elemento para generar la nueva lista.

# 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))

Producción :

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

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *