Search code examples
pythonlist-comprehension

iterable in Python list comprehension


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?


Solution

  • 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.