What don't I understand about the order of execution and/or operations in Python 2.7?

Question:

I have a list and I am trying to obtain either a set or a list of the unique items in that list. I also need to remove all instances of a specific item from the list, which in this case is 'USD'.

currencies = ['AUD', 'AUD', 'CAD', 'CHF', 'EUR', 'GBp', 'GBp', 'HKD', 'JPY', 'KRW', 'NOK', 'SEK', 'TWD', 'USD', 'USD', 'ZAr']

I initially tried,

foreign_currencies = set(currencies).discard('USD')

but noticed that the function was returning None.

In order to get it to work, I had to do it in two steps.

foreign_currencies = set(currencies)
foreign_currencies = foreign_currencies.discard('USD')

However, I don’t see why this would resolve the issue. Can anyone tell me why this is the case and/or explain what I am not understanding about the order of execution? If .discard modifies the set in-place and returns None, I would expect the results of the second example to be the same as the first. In the first example, is .discard() being called before the set is constructed? Is it something deeper that I am not getting?

EDIT: Although the responses in "https://stackoverflow.com/questions/1682567/why-does-pythons-list-append-evaluate-to-false" answer my question, my question was not a duplicate. The question posed was not the same, the answer is.

Asked By: Kapocsi

||

Answers:

Because discard does not return any output.It does an in place removal.

You need to do

foreign_currencies = set(currencies)
foreign_currencies.discard('USD') #do not assign this as `discard does not return anything.
print foreign_currencies #now you have the currect result
Answered By: vks

As vks said, discard is an in place operation. This is what your code ‘wants’ to do:

foreign_currencies = set(currencies)
foreign_currencies.discard('USD')
Answered By: Noam Kremen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.