List, dictionary and set comprehension

List, dictionary and set comprehension

Demonstration of Python comprehension on the list, set and dictionary

·

3 min read

List comprehension

Python list data types are one of the fundamental elements of data structure. With the list comprehension feature, we can generate a series of lists from a list. For example, the simplest form of list comprehension is to perform a shallow copy of a list as follows:

a_list = [1, 2, 3, 4, 5]
b_list = a_list[:]

What we are saying here is that hey Python just performs copies of all the elements by value or member by member. So, a change in the new list won't change the original list. For example

list member-by-member copy example

In the above python shell, we see that the two variables contain equal values but refer to different objects.

By the way Python **is** operator compares two variables and returns True if they reference the same object. If the two variables reference different objects, the is operator returns False as in the above example. In other words, the **is** operator compares the identity of two variables and returns True if they reference the same object.

Here is another way to achieve the same result using for loop:

b_list = []
for i in a_list:
    b_list.append(i)

The general syntax for list comprehension is:

new_list = [value for_statement if_expression]

value aka expression: takes a value directly from the list for_statement: one or more for statements with conditions on the member if clauses: for evaluating some conditions Let's see the following example:

>>>[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

The above code snipper two for loops to check conditions of two values in different lists which in turn produces a tuple of lists based on the if clauses.

Set comprehension

A set is an unordered collection with no duplicate elements. The same concept as list comprehension will be used except that the syntax for the set is {}. For example, let's create a set from a given list with the following set comprehension.

>>> a_list = [1, 2, -2, 1, -1, 2, 3]
>>> new_set = {i for i in a_list if i > 0}
>>> new_set
>>> {1, 2, 3}

You may have noticed already that there are no duplicate values because the elimination of duplicates happens automatically as we are creating a set via {}.

Dictionary comprehension

We are going to use a similar approach but with a little complexity. In a dictionary comprehension, it is necessary to create a loop that generates key-value pairs, using the syntax:

key:value Assume we have a list of tuples that we'd like to be the basis for our newly generated dictionary.

>>> list_tuples = [('Netherlands', 'Amsterdam'), ('Germany', 'Berlin')]
>>> new_dict = { i[0] : i[1] for i in list_tuples }

Note the use of the colon (:) in the key-value expression. Then if we want to check, let's evaluate the following:

>>> new_dict['Netherlands']
'Amsterdam'
>>>

Let's see one more example of how to create a dictionary from two given lists.

>>> countries = ['China', 'India', 'U.S.A', 'Indonesia']
>>> population = [1_452_661_848, 1_413_052_163, 335_683_841, 280_581_836]
>>> four_largest_countries_by_population = { countries[i]: population[i] for i in range(len(keys)) }
>>> four_largest_countries_by_population
{'China': 1452661848, 'India': 1413052163, 'U.S.A': 335683841, 'Indonesia': 280581836}
>>>

Note: in the above, we assume both lists have the same length.

We can even improve the performance of the code in the above example by using the built-in zip function to merge the lists. If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.

Final words

Hope this sheds some light on those who begin to learn python, and a refresher to those who have solid knowledge. As usual, you are welcome to drop your comments even for some