0

I have a list of tuples with the following fields: tappeto.storico = [(date, nr_bought)] I want to increase nr_bought if date == current_date. If I use the explicit way:

for item in tappeto.storico:
    if item.date == current_date:
        item.nr_bought += 1
        break

works perfectly but if I try to use the list comprehension:

[item.nr_bought + 1 if item.date == current_date for item in tappeto.storico]

it goes through the items but looks like the if statement doesn't work. Where am I wrong?

Fabio
  • 129
  • 1
  • 7
  • Your attempt uses invalid syntax, it won't run at all. Filters go *at the end*, not in the expression part: `[item.nr_bought + 1 for item in tappeto.storico if item.date == current_date]`, or you use a *conditional expression* (which uses three parts, with `else`: `.. if .. else ..`), so `[item.nr_bought + 1 if item.date == current_date else item.nr_bought for item in tappeto.storico]`. – Martijn Pieters Oct 11 '16 at 09:30
  • Not that your code actually would work on tuples; are they perhaps *named* tuples? Normal tuples don't have attributes like that. – Martijn Pieters Oct 11 '16 at 09:33
  • They appear not to be tuples, if the first one works perfectly. – RemcoGerlich Oct 11 '16 at 09:33
  • @MartijnPieters: if they're namedtuples then the first would only update the local variable item and not the list, right? Yet he claims it works perfectly. – RemcoGerlich Oct 11 '16 at 09:34
  • @RemcoGerlich: it indeed would only update the local variable. I guess it 'works' in that it doesn't raise a syntax error like the list comp attempt does. It would actually raise an exception when run though as `+=` would attempt to mutate the tuple and fail. – Martijn Pieters Oct 11 '16 at 09:37

0 Answers0