Python List Comprehensions
Introduction
Lists are easy to recognize in Python. Whenever we see brackets ‘[]’, we know that lists are afoot. Declaring lists is just about as easy as gets in Python.
Here’s a walkthrough.
The first step:
my_list = []
Then, if we want to add anything to the list, we just call:
my_list.append() # one element
or
my_list.extend() # several elements
Nothing could be easier to read, and if your lists aren’t broken, why fix them? There are actually two major reasons, and even a bonus one:
The two major reasons are:
- You can produce working code quicker.
- Code with List Comprehensions is even easier to read (with a bit of practice).
The bonus reason:
- ListComps have a moderate performance advantage.
(Note: You may see List Comprehensions variously referred to as comprehensions, List Comprehensions, or ListComps.)
The reason I consider the performance advantage not to be a major factor is because if performance is a major concern, you might want to look at a different datatype altogether – such as Dictionary.
For List Comprehensions or Dictionary Comprehensions beginners, it can be hard to see how they could be easier to read than the good ol’ list declaration and manipulation using explicit methods. The answer is practice, and room for error. There’s much less room for error in a ListComp than a nested for loop. Because comprehensions usually (but not necessarily) take place on a single line, the brain can digest more meaning at once.
With practice, you’ll prefer to read code that is written with comprehensions because:
- You automatically know the intended output.
- You can see the input and the way it’s modified.
- Like Lambda functions, you can easily pass ListComps dynamically.
When to use ListComps
What exactly are List Comprehensions, and why would we need them when lists are so flexible out-of-the-box?
List Comprehensions are used when a list should be populated consistently according to a known pattern, often to extract data from an existing collection.
For example, let’s say you have some JSON data from an API, which, when parsed by a library of requests, winds up being a list of thousands of phone numbers with each stored as a dictionary with several fields:
phones = [
{
'number': '111-111-1111',
'label': 'phone',
'extension': '1234',
},
{
'number': '222-222-2222',
'label': 'mobile',
'extension': None,
}
]
What if our assignment was just to print out a list of numbers?
Of course, we can iterate through the list traditionally:
my_phone_list = []
for phone in phones:
my_phone_list.append(phone['number'])
>>>my_phone_list
['111-111-1111', '222-222-2222']
A List Comprehension which accomplishes the same result takes only one line:
>>>[phone['number'] for phone in phones]
['111-111-1111', '222-222-2222']
A List Comprehension follows the basic pattern…
[ <do something to item> for <item> in <list>]
…or if you want to keep the result around:
output_list = [ <manipulate item> for <item> in <input list> ]
Remember, if a List Comprehension appears confusing, as they often do at first, feel free to break it up into a for loop:
<output list>
For <item> in <input list>:
output_list.append(< manipulate item>)