Reputation: 25
If I have:
usernames = [user.get('username') for user in json.loads(users)]
Will the json.loads be called once as in normal for loop or many times on each iteration?
Upvotes: 1
Views: 162
Reputation: 181785
Don't worry: it is called only once, although the language reference isn't exactly clear on this point:
The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those that would be produced by considering each of the
for
orif
clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.
Upvotes: 1
Reputation: 1476
It will be called only once as in a normal for-loop. For example:
x = [2,4,6,8,10]
y = [i/2 for i in x]
Output:
>>> y
[1.0, 2.0, 3.0, 4.0, 5.0]
Here each element of x
is called once as i
and divided by 2 as i/2
. Similarly, json.loads(users)
will also be called once.
Upvotes: 1