Comprehension(List, Dictionary &Set) in Python
In a previous post, we explained different iteration techniques that can be done using Python.
Comprehension is another kind of iteration/looping through a data set . A comprehension creates a new list, set, or dictionary by applying an operation to each item in an iterable(e.g. list, set, dictionary etc.)
Syntax:
List comprehension: [ expression for item in iterable]
Dictionary comprehension: { key: value_expression for item in iterable}
Set comprehension: {item for item in iterable}
Taking a look at the above syntax, List comprehension uses square brackets([]), while Dictionary and Set comprehension use the curly braces({}).
Example:
Say we a list and we need to generate a new list with squares of the original list:
[*]Snippet
my_list = [2,3,4,5,6]
square_list = [ element**2 for element in my_list]
print(square_list)
[*]Output
[4, 9, 16, 25, 36]
Remember that comprehension creates a new list/set/dict by iterating through element in original iterable. It is just a shortcut for a for-loop
Using the initial ‘my_list’, let’s create a new dictionary
[*]
my_list = [2, 3,4,5,6]
new_dict ={ item:item*2 for item in my_list }
print(new_dict)
[*]Output
{2: 4, 3: 6, 4: 8, 5: 10, 6: 12}
Set comprehension: This is similar to how we created the dictionary comprehension.The only difference is that there’s no need for keys.
[*]
my_list = [2, 3,4,5,6]
new_set ={ item + 1 for item in my_list }
print(new_set)
[*]Output
{3, 4, 5, 6, 7}
Guard/Check:
For each element in the original list/dict/set, it is possible to put additional conditional if statement before adding an element to the new data set.
This example allows item greater than 4 in the new list:
[*]Snippet
my_list = [2, 3,4,5,6]
new_list = [ element for element in my_list if element > 4]
print(new_list)
[*]Output
[5, 6]
The syntax for conditional checks looks like this:
new_list = [expression for item in iterable (if conditional)]
Say if the value is not greater that 4 we want to provided our own custom/default value using the else statement, then the conditional check can follow this direction:
[expression (if conditional) for item in iterable ]
[*]snippet
my_list = [2, 3,4,5,6]
new_list = [ element if element > 4 else 10 for element in my_list ]
print(new_list)
[*]Output
[10, 10, 10, 5, 6]
Comprehension, as mentioned above, is a shortcut and it lets you write code that’s easy to read. Though not the perfect solution in all circumstances especially when dealing with large data set. The drawback is in the fact that comprehension use more memory.
Thanks for reading and feel free to explore my video collection on YouTube for more educational content. Don’t forget to subscribe to the channel to stay updated with future releases.