Search code examples
pythonlistindexinginsertrange

Add elements in a list at the n index of a other list


calibres_prix =['115-135', '1.87'], ['136-165', '1.97'], ['150-180', '1.97'], 
    ['190-220', '1.97'], ['80-95', '1.42'], ['95-115', '1.52'], ['150-180', '1.82'], 
    ['115-135', '1.72'], ['136-165', '1.82'], ['150-180', '1.82'], ['190-220', '1.82'], 
    ['80-95', '1.42'], ['95-115', '1.72'], ['115-135', '1.92'],  ['136-165', '2.02'], 
    ['150-180', '2.02'], ['190-220', '2.02'], ['80-95', '1.27'], ['95-115', '1.57'],
    ['115-135', '1.77'], ['136-165', '1.87'],  ['150-180', '1.87'], ['190-220', '1.87'], 
    ['80-95', '1.37'], ['95-115', '1.67'], ['115-135', '1.87'], ['136-165', '1.97'],
    ['190-220', '1.82'], ['150-180', '1.97'], ['190-220', '1.97'], ['80-95', '1.22'], 
    ['95-115', '1.45'], ['115-135', '1.65'], ['136-165', '1.82'], ['95-115', '1.52']......


varieties=["GOLDEN","GALA","OPAL","GRANNY","CANADE GRISE", "PINK ROSE",
           "CHANTECLER","RED","GOLDRESH","BRAEBURN","STORY"]

Hi everbody, I want to insert to the list calibres_prix the name of the variety. To the calibres_prix [0:23] the varieties[0], to the calibres_prix [24:47] the varieties[1], etc .... i have 264 lists for calibres_prix

I want this output :

['GOLDEN','115-135', '1.87']
....
['GALA','190-220', '1.97']

I try this:

for i in range(0,len(calibres_prix),24):
    j=i+24
    for l in range(0,len(varieties),1):
        for c in calibres_prix[i:j]:
            c.insert(0,varieties[l])

Solution

  • Close! You are appending all the varieties to each list in your loop, however.

    You could try this instead:

    for i in range(0, len(calibres_prix)):
        calibres_prix[i] = [varieties[i//24]] + calibres_prix[i]
    

    For each list in calibres_prix (I have assumed this is a list of lists, as you haven't included an initial [), add the i//24 th varieties value at the start.