Divide list in list of lists

1

I have a list and I want to divide it into a list of lists every 3 values.

lista = ['131997','https://www.google.com.ar/','google.com.ar','134930','https://www.a-a.com/','a-a.com']

What I'm looking for is exactly this:

lista = [['131997','https://www.google.com.ar/','google.com.ar'],['134930','https://www.a-a.com/','a-a.com']]
    
asked by Martin Bouhier 30.01.2018 в 19:26
source

2 answers

3

With this code you could do it, assuming that the original list has N elements and N is a multiple of 3:

lista = ['131997','https://www.google.com.ar/','google.com.ar','134930','https://www.a-a.com/','a-a.com']

lista_nueva = []
for i in range(0, len(lista), 3):
    lista_nueva.append(lista[i:i+3])
print(lista_nueva)
    
answered by 30.01.2018 в 19:35
0

A super compact form by understanding lists is the following:

nueva_lista = [lista[i:i+3] for i in range(0, len(lista), 3)]

We use an optional parameter functionality step of range() that allows us to return ranges in steps, in this case of 3. Then we are simply doing a slice of the list: lista[i:i+3] for each index + 3.

    
answered by 30.01.2018 в 22:48