Reputation: 967
I'm trying to figure out this python what the brackets mean around this python statement:
[self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True) for bid in json_doc['bids']]
I'm trying to figure out what the brackets are doing in this. Is it modifying a list in place? I don't get it and I can't figure out how to ask google for the right answer. This is the complete function right here:
def get_level3(self, json_doc=None):
if not json_doc:
json_doc = requests.get('http://api.exchange.coinbase.com/products/BTC-USD/book', params={'level': 3}).json()
[self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True) for bid in json_doc['bids']]
[self.asks.insert_order(ask[2], Decimal(ask[1]), Decimal(ask[0]), initial=True) for ask in json_doc['asks']]
self.level3_sequence = json_doc['sequence']
Upvotes: 0
Views: 143
Reputation: 4341
In essence it means: Do something for every item in the list
Here's a simple example:
exampleList = [1, 2, 3, 4, 5]
#for every item in exampleList, replace it with a value one greater
[item + 1 for item in exampleList]
print(exampleList)
#[2, 3, 4, 5, 6]
List comprehensions are useful when you need do something relatively simple for every item in a list
[self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True) for bid in json_doc['bids']]
The list we are working with is json_doc['bids']
. So for every bid in json_doc['bids']
we insert a new bid with self.bids.insert_order()
with all the qualities of that bid which are stored as bid[0]
, bid[1]
etc. In summary, this list comprehension calls the function self.bids.insert_order()
for every bid in your json list
Upvotes: 3
Reputation: 9010
To begin with, a list comprehension is a way of constructing a list inline. Say you want to make a list of the first five square numbers. One way would be:
square_list = []
for i in range(1,6):
square_list.append(i**2)
# square_list = [1, 4, 9, 16, 25]
Python has some syntactical sugar to ease this process.
square_list = [i**2 for i in range(1,6)]
I think the most important thing to note is that your example is questionable code. It's using a list comprehension to repeatedly apply a function. That line generates a list and immediately throws it away. In the context of the previous example, it might be akin to:
square_list = []
[square_list.append(i**2) for i in range(1,6)]
This, in general, is kind of a silly structure. It would be better to use either of the first two formulations (rather than mix them). In my opinion, the line you're confused about would be better off as an explicit loop.
for bid in json_doc['bids']:
self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True)
This way, it is clear that the object self.bids
is being altered. Also, you probably wouldn't be asking this question if it was written this way.
Upvotes: 1