Python | Insertar lista en otra lista

El problema de insertar un número en cualquier índice es bastante común. Pero a veces necesitamos insertar la lista completa en otra lista. Este tipo de problemas ocurren en Machine Learning mientras se juega con datos. Analicemos ciertas formas en que se puede resolver este problema.

Método #1: Usar el insert()bucle +
En este método, insertamos un elemento de uno en uno usando la función de inserción. De esta manera agregamos todos los elementos de la lista en el índice especificado en otra lista.

# Python3 code to demonstrate 
# to insert one list in another
# using insert() + loop
  
# initializing lists 
test_list = [4, 5, 6, 3, 9]
insert_list = [2, 3]
  
# initializing position
pos = 2
  
# printing original list
print ("The original list is : " + str(test_list))
  
# printing insert list 
print ("The list to be inserted is : " + str(insert_list))
  
# using insert() + loop
# to insert one list in another
for i in range(len(insert_list)):
    test_list.insert(i + pos, insert_list[i])
  
# printing result 
print ("The list after insertion is : " +  str(test_list))

Producción :

The original list is : [4, 5, 6, 3, 9]
The list to be inserted is : [2, 3]
The list after insertion is : [4, 5, 2, 3, 6, 3, 9]

 
Método n.º 2: Usar el corte de listas
Esta es la forma más pythonica y elegante de realizar esta tarea en particular. En este método, simplemente cortamos la lista donde necesitamos agregar el elemento y asignamos la lista que se insertará.

# Python3 code to demonstrate 
# to insert one list in another
# using list slicing
  
# initializing lists 
test_list = [4, 5, 6, 3, 9]
insert_list = [2, 3]
  
# initializing position
pos = 2
  
# printing original list
print ("The original list is : " + str(test_list))
  
# printing insert list 
print ("The list to be inserted is : " + str(insert_list))
  
# using list slicing
# to insert one list in another
test_list[pos:pos] = insert_list
  
# printing result 
print ("The list after insertion is : " +  str(test_list))

Producción :

The original list is : [4, 5, 6, 3, 9]
The list to be inserted is : [2, 3]
The list after insertion is : [4, 5, 2, 3, 6, 3, 9]

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 *