monsterkittykitty
monsterkittykitty

Reputation: 65

Create two lists with one use of Python list comprehension?

I have a list of objects that each contain several class variables. I'm interested in a couple of those class variables, and I'd like to create two separate lists, each containing a different class variable from that list of objects.

The object class looks something like this:

class Pie: 
     def __init__(self, array1, array2, timestamp, latitude, longitude):
          self.array1 = array1
          self.array2 = array2
          self.timestamp = timestamp
          self.latitude = latitude
          self.longitude = longitude

And I have a list that contains a bunch of those objects:

list = [pie_instance1, pie_instance2, pie_instance3, pie_instance4, pie_instance5]

I'd like to create a list containing array1, and another list containing array2.

I started out just using list comprehension twice:

list_of_array1 = [x.array1 for x in list]
list_of_array2 = [x.array2 for x in list]

But it seems not so efficient to iterate over the entire list twice (the list in my actual code is very large).

So I tried this instead:

temp = np.array([[x.array1, x.array1] for x in list])
list_of_array1 = temp[:, 0]
list_of_array2 = temp[:, 1]

It works, but I'm wondering if there's a one-step way to achieve this with list comprehension? Or some other way you'd recommend? Thanks in advance!

Upvotes: 1

Views: 1392

Answers (3)

mkrieger1
mkrieger1

Reputation: 23144

To iterate over list only once, but create two result lists, use an ordinary for loop:

list_of_array1 = []
list_of_array2 = []
for x in list:
    list_of_array1.append(x.array1)
    list_of_array2.append(x.array2)

But your original solution of using two list comprehensions was also fine. The performance difference is probably negligible.

Upvotes: 2

Shradha
Shradha

Reputation: 2442

The very definition of a list comprehension is to produce one list object.

Don't use list comprehensions here. Just use an ordinary loop:

list_of_array1 = []
list_of_array2 = []
for x in list:
    list_of_array1.append(x.array1)
    list_of_array2.append(x.array2)

This leaves you with just one loop to execute.

Upvotes: 5

Xmaster6y
Xmaster6y

Reputation: 156

You can use the zip function:

L1, L2 = zip(*[(x.array1,x.array2) for x in list])

It's up to you to change the comprehension...

Upvotes: 3

Related Questions