List Comprehension in Python

From Knowledge Center
Jump to: navigation, search

Example of List Comprehensions:

Our Data:

>>> u = {"users": [{"userid": "ruanb"}, {"userid": "stefanb"}]}
>>> u['users']
[{'userid': 'ruanb'}, {'userid': 'stefanb'}]

Using a For Loop to Access the Data:

>>> for i in u['users']:
...     i['userid']
...
'ruanb'
'stefanb'

Using List Comprehension to Access the Data:

>>> [i['userid'] for i in u['users']]
['ruanb', 'stefanb']

For loop with an If statement:

>>> for i in u['users']:
...     if i['userid'] == 'ruanb':
...         i['userid']
...
'ruanb'

List Comprehension with a If statement

>>> [i['userid'] for i in u['users'] if i['userid'] == 'ruanb']
['ruanb']