0

I'm not too familiar with Python so forgive me if these two things are unrelated.

I'm working with an ORM for the first time (SQLALCHEMY) and it's interesting but quite confusing. Today I ran into a weird issue and I'm pretty puzzled but hoping someone can clear it up for me. Essentially I want to know what the difference between this:

[[x.item for x in y.items] for y in yy]

and this:

[x.item for x in [y.items for y in yy]]

Basically, yy is the result set of a query (Y.query.all()) and items is a relationship defined in the sqlalchemy db model. In the second loop, I am told that x has no property item but in the first loop my code is valid. I am glad that I finally got this to work but I am very confused as to why it works.

Shouldn't y.items have the same value in both cases?

Is nesting from left to right just a rule in list comprehension?

Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65

1 Answers1

2

Strictly speaking, note that [[x.item for x in y.items] for y in yy] is equivalent to

list_ = []
for y in yy:
    list_.append([x.item for x in y.items])

okay for that.


While [x.item for x in [y.items for y in yy]], is equivalent to
list_ = []
for x in [y.items for y in yy]:
    list_.append(x.item)

or put differently and using a more meaningful name than x

list_ = []
for y_items in [y.items for y in yy]:
    list_.append(y_items.item)

Does each y_items possess an item property ? No it does not. A contrario each of the elements contained in y_items does, as outlined before by what you call "first loop", i.e. [x.item for x in y.items].


To summarize,

Shouldn't y.items have the same value in both cases?

No because in the "first loop" you get the item property of each element of y.items while in the "second loop" you (try to) get the item property of y.items itself.

keepAlive
  • 6,369
  • 5
  • 24
  • 39