Skip to content Skip to sidebar Skip to footer

Python 3, List Comprehensions, Scope And How To Compare Against External Variables

I have a class representing items of stock and their value: class stock: def __init__(self, stockName, stockType, value): self.name = stockName self.type = sto

Solution 1:

This doesn't work. I know Why - it is because in Python 3 list comprehensions have their own scope (See detailed answer here: Accessing class variables from a list comprehension in the class definition )

That’s actually not true. I mean, of course that answer in that question is correct but that’s not what is happening here. That question is only relevant for expressions that happen in the class body at definition time. If you are e.g. within a method though then there is no problem at all.

However, what likely fails (“likely” because you didn’t supply the error message), is that the target list stockTypeValue isn’t initialized.

>>> stockTypeValue[0] ='something'
Traceback (most recent calllast):
  File "<pyshell#4>", line 1, in<module>
    stockTypeValue[0] ='something'
NameError: name 'stockTypeValue'isnot defined

So we can define it now and assign an empty list; but the list is still empty:

>>> stockTypeValue = []
>>> stockTypeValue[0] ='something'
Traceback (most recent calllast):
  File "<pyshell#6>", line 1, in<module>
    stockTypeValue[0] ='something'
IndexError: list assignment index outofrange

Instead, you would have to append the result to the empty list:

>>>stockTypeValue.append('something')>>>stockTypeValue[0]
'something'

Replaying your example:

>>>stockList = []>>>stockList.append(stock('product A', 'shirt', 53.2))>>>stockList.append(stock('product B', 'hat', 20.2))>>>sum([s.value for s in stockList if s.type == 'shirt'])
53.2
>>>stockType = 'shirt'>>>sum([s.value for s in stockList if s.type == stockType])
53.2

Post a Comment for "Python 3, List Comprehensions, Scope And How To Compare Against External Variables"