List, dictionary and set comprehension

eritech

Eritech

Posted on November 20, 2022

List, dictionary and set comprehension

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[:] 
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

The general syntax for list comprehension is:

new_list = [value for_statement if_expression]
Enter fullscreen mode Exit fullscreen mode

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)]
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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'
>>>
Enter fullscreen mode Exit fullscreen mode

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}
>>>
Enter fullscreen mode Exit fullscreen mode

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 broken sentences, ideas or concepts. Thanks for reading this far.

💖 💪 🙅 🚩
eritech
Eritech

Posted on November 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

List, dictionary and set comprehension