0

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
Ariel Montes
  • 256
  • 2
  • 6
  • " or some way to do it with list comprehension (I couldn't do it) to make it more efficient" list comprehensions aren't more efficient than loops, they are implemented as loops – juanpa.arrivillaga Feb 18 '21 at 09:44
  • Just adding that `range` takes an optional `step` parameter. – Dschoni Feb 18 '21 at 09:46
  • 2
    In any case, there are various general solutions in the linked duplicate, but you can use `result = [Person(*data[i:i+3]) for i in range(0, len(data), 3)]` – juanpa.arrivillaga Feb 18 '21 at 09:47
  • I know, I meant to avoid the declaration of the three index variables using some inbuilt function that allows me to do everything in a single line – Ariel Montes Feb 18 '21 at 09:47
  • 2
    @ArielMontes I would avoid simply trying to do things on one line. Short code isn't some intrinsic virtue, you want *readable, maintainable code*. On multiple lines, something like `for i in range(0, len(data), 3): name, lastname, age = data[i:i+3]; result.append(Person(name, lastname, age))` Why avoid new variables when they aid in understanding what is going on? You generally write code once but read it many times. – juanpa.arrivillaga Feb 18 '21 at 09:50
  • I didn't know that about slicing, thanks a lot – Ariel Montes Feb 18 '21 at 09:52

0 Answers0