I have a list in which every 3 elements an object should be defined. I was wondering if there is a function in Python that can iterate over items in a list three at a time or some way to do it with list comprehension (I couldn't do it) to make it more efficient since the actual list is very large.
What I did was to divide by 3 the length of the list to iterate in it a number of times equivalent to a third (1/3) of the total of its elements, thus accessing the three elements and increasing its three indexes (for the next iteration) in each cycle.
The code I have works, I just want to avoid reinventing the wheel in case there is something better.
data = ["John", "Doe", 30, "Jane", "Doe", 28] # Example data
persons=[] # Processed data
class Person:
def __init__(self, name, lastname, age):
self.name = name
self.lastname = lastname
self.age = age
x, y, z = 0, 1, 2 # Index
for i in range( int(len(data) / 3) ): # Iterates every 3 elements
persons.append( Person(data[x], data[y], data[z]) ) # Create objects
x+=3; y+=3; z+=3 # Index increment