To not complicate your life, create a function that runs the list from the second position to the last position. This is done by placing after the list between braces [1:-1]
. This syntax denotes that the list is copied from the second position to the end, excluding the last item.
Remember that in Python the indexes start from 0
, so the second position is 1
.
The -1
would be the last position
Using the append
method
# -*- coding: utf-8 -*-
lista_x = [2, 3, 4, 5]
lista_y = [6, 7, 8, 9]
def no_entiendo_para_que_es_esto(lista):
resultado = [] # creamos una nueva lista para trabajar
resultado.append(lista[0]) # agregamos a la lista el primer item
# recorremos desde la posición 2 hasta la ante ultima posición
for item in lista[1:-1]:
# añadimos a la lista dos veces el item actual.
resultado.append(item)
resultado.append(item)
resultado.append(lista[-1]) # agregamos a la lista el ultimo item
return resultado
print no_entiendo_para_que_es_esto(lista_x)
print no_entiendo_para_que_es_esto(lista_y)
Using the insert
method
# -*- coding: utf-8 -*-
def no_entiendo_para_que_es_esto2(lista):
resultado = lista[:] # hacemos una copia exacta de la lista original
# creamos un rango desde el indice 1 hasta el ante último.
for indice in range(len(lista))[1:-1]:
# Debemos multiplicar por dos el indice al que queremos insertar el
# valor, ya que la lista va creciendo y los item moviendose una
# posicion en cada iteración.
resultado.insert(indice * 2, lista[indice])
return resultado
print no_entiendo_para_que_es_esto2(['a', 'b', 'c', 'd', 'e'])
print no_entiendo_para_que_es_esto2(['uno', 'segundo', 'tercero', 'ultimo'])
print no_entiendo_para_que_es_esto2([1, 2, 3, 4, 5, 6, 7])
Using sum
on tuples generated from an iteration
def solucion3(lista):
return sum([(item, item) for item in lista], ())[1:-1]
print solucion3([2, 3, 4, 5])
# (2, 3, 3, 4, 4, 5)
print solucion3([2, 3, 4, 5, 6])
# (2, 3, 3, 4, 4, 5, 5, 6)
print solucion3(['a', 'b', 'c', 'd'])
# ('a', 'b', 'b', 'c', 'c', 'd')
print solucion3(['a', 'b', 'c', 'd', 'c'])
# ('a', 'b', 'b', 'c', 'c', 'd', 'd', 'c')