What is the difference between list comprehension and dictionary comprehension?

List and dictionary comprehensions in Python

To understand the basis of list and dictionary comprehensions, let’s first go over for-loops.

for-loops

In Python, a for-loop is perfect for handling repetitive programming tasks, as it can be used to iterate over a sequence, such as a list, dictionary, or string.

Let’s take a look at a simple example using a list:

words = ['cat', 'window', 'ball']

for x in words:

print[x]

The result is each element printed one by one, in a separate line:

cat

window

ball

As you get to grips with more complex for-loops, and subsequently list comprehensions and dictionary comprehensions, it is useful to understand the logic behind them.

A for-loop works by taking the first element of the iterable [in the above case, a list], and checking whether it exists. If it does, the required action is performed [in the above case, print]. The loop then starts again and looks for the next element. If that element exists the required action is performed again. This behaviour is repeated until no more elements are found, and the loop ends.

Using the range[] function

The very useful range[] function is an in-built Python function and is used almost exclusively with for-loops. Essentially, its purpose is to generate a sequence of numbers.

Let’s look at an example to see how it works:

for i in range[5]:

print[i]

The result is:

0

1

2

3

4

Be aware that the range[] function starts from 0, so range[5] will return the numbers 0 to 4, rather than 1 to 5.

By default, the sequence will start from 0, increment in steps of 1, and end on a specified number. It is possible, however, to define the first element, the last element, and the step size as range[first, last, step_size].

List comprehensions

List comprehensions provide a more compact and elegant way to create lists than for-loops, and also allow you to create lists from existing lists.

List comprehensions are constructed from brackets containing an expression, which is followed by a for clause, that is [item-expression for item in iterator] or [x for x in iterator], and can then be followed by further for or if clauses: [item-expression for item in iterator if conditional].

Let’s look at some examples to see how they work:

x = [i for i in range[10]]

Produces the result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

And utilizing a conditional statement:

x = [i for i in range[10] if i > 5]

Returns the list:

[6, 7, 8, 9]

because the condition i > 5 is checked.

As well as being more concise and readable than their for-loop equivalents, list comprehensions are also notably faster.

Nested list comprehensions

Generating, transposing, and flattening lists of lists becomes much easier with nested list comprehensions. Most of the keywords and elements are similar to basic list comprehensions, just used again to go another level deeper.

To demonstrate, consider the following example:

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

The result is:

[[1, 3], [1, 4], [2, 3], [2, 1], [2, 4], [3, 1], [3, 4]]

Complex expressions and nested functions

You can also use functions and complex expressions inside list comprehensions.

For example:

from math import pi # import pi number from math module

[str[round[pi, i]] for i in range[1, 6]]

Returns:

['3.1', '3.14', '3.142', '3.1416', '3.14159']

List comprehensions are ideal for producing more compact lines of code. They can also be used to completely replace for-loops, as well as map[], filter[], and reduce [] functions, which are often used alongside lambda functions.

Dictionary comprehensions

In Python, dictionary comprehensions are very similar to list comprehensions – only for dictionaries. They provide an elegant method of creating a dictionary from an iterable or transforming one dictionary into another.

The syntax is similar to that used for list comprehension, namely {key: item-expression for item in iterator}, but note the inclusion of the expression pair [key:value].

Let’s look at a simple example to make a dictionary. The code can be written as

dict[[[i, i+10] for i in range[4]]]

which is equivalent to:

{i : i+10 for i in range[4]}

In both cases, the return value is:

{0: 10, 1: 11, 2: 12, 3: 13}

This basic syntax can also be followed by additional for or if clauses: {key: item-expression for item in iterator if conditional}.

Using an if statement allows you to filter out values to create your new dictionary.

For example:

{i : i+10 for i in range[10] if i > 5}

Returns:

{6: 16, 7: 17, 8: 18, 9: 19}

Similar to list comprehensions, dictionary comprehensions are also a powerful alternative to for-loops and lambda functions. For-loops, and nested for-loops in particular, can become complicated and confusing. Dictionary comprehensions offer a more compact way of writing the same code, making it easier to read and understand.

Nested dictionary comprehension

In Python, dictionary comprehensions can also be nested to create one dictionary comprehension inside another.

For example:

{[k, v]: k+v for k in range[2] for v in range[2]}

Returns:

{[0, 0]: 0, [0, 1]: 1, [1, 0]: 1, [1, 1]: 2}

Take care when using nested dictionary comprehensions with complicated dictionary structures. In such cases, dictionary comprehensions also become more complicated and can negate the benefit of trying to produce concise, understandable code.

List, Set, Dictionary Comprehensions in Python

Let’s learn about the list, dictionary, set comprehensions in python.

Photo by Kara Eads on Unsplash

Comprehensions in Python:

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses.

4 Types of Comprehensions In Python

Only use them for concise and readable

Christopher Tao

Jan 25, 2021·7 min read

As one of the most widely used “Pythonic” syntax in Python, you must have ever heard List Comprehension or have already used it frequently. It is almost a must-have section in various Python elementary tutorials. However, did you know that there are actually 4 types of “comprehension” in Python rather than only for the lists? You may also have heard or ever used Dictionary Comprehension, but might not for the set and generator.

In this article, I’ll introduce all the 4 types comprehensions in Python with examples. In the last section, I also want to give an example to show you when not to use comprehensions for better readability. Use it with care, please!

Video

I have created a video on this blog post for you to watch if you prefer:

Lists vs. Dictionaries

Before we dive into the specifics of List and Dictionary Comprehensions, we first need to know the difference between an actual List and a Dictionary. If you already know, you’re welcome to skip this section.

Lists

In Python, lists are an array of objects that are stored in sequential order. They are represented using [] [square brackets]. Unlike many other languages, a list can contain a mixture of different data types.

The following is an example of a Python list:

[123, "string", True, 'hi']

Dictionaries

Dictionaries are similar to lists in that they store an array of objects, but these objects are accessed using keys and the object we are accessing is called the value. In Python, these are represented using {} [curly braces].

The following is an example of a Python dictionary:

{"name" : "Ivan", "surname" : "Kahl", "age" : 19}

List & Dict Comprehensions in Python

May 27, 2018
Data Structures, Python

Python comprehensions are syntactic sugar constructs that provide a way to build a list, dictionary or set from a starting list, dictionary or set whilst altering or filtering elements.

Comprehensions follow mathematical set builder notation rather than map and filter functions.

Python Dictionary

A dictionary in Python is a collection of items accessed by a specific key rather than by index. What does this mean?

Imagine a dictionary in the real world... when you need to look up the meaning of a word, you try to find the meaning using the word itself and not the possible index of the word. Python dictionaries work with the same concept, the word whose meaning you are looking for is the key and the meaning of the word is the value, you do not need to know the index of the word in a dictionary to find its meaning.

Note: The keys in a dictionary have to be hashable.

Hashing is the process of running an item through a specific kind of function. This function is called a "hash function". This hash function returns a unique output for a unique input value. Integers, floating point numbers, strings, tuples, and frozensets are hashable. While lists, dictionaries, and sets other than frozensets are not. Hashing is a somewhat complex topic and this is only the basic concept behind hashing.

You can initialize a dictionary in Python this way:

a = {'apple': 'fruit', 'beetroot': 'vegetable', 'cake': 'dessert'} a['doughnut'] = 'snack' print[a['apple']] fruit print[a[0]] --------------------------------------------------------------------------- KeyError Traceback [most recent call last] in [] ----> 1 print[a[0]] KeyError: 0

Note that the line of code above gives you an error message because there doesn't exist a key '0'.

The items in a dictionary can have any data type. Check out some more examples of a dictionary to get a hang of it:

a = {'one': 1, 'two': 'to', 'three': 3.0, 'four': [4,4.0]} print[a] {'four': [4, 4.0], 'two': 'to', 'three': 3.0, 'one': 1} # Update a dictionary a['one'] = 1.0 print[a] {'four': [4, 4.0], 'two': 'to', 'three': 3.0, 'one': 1.0} # Delete a single element del a['one'] print[a] {'four': [4, 4.0], 'two': 'to', 'three': 3.0} # Delete all elements in the dictionary a.clear[] print[a] {} # Delete the dictionary del a print[a] --------------------------------------------------------------------------- NameError Traceback [most recent call last] in [] 1 del a #Deletes the dictionary ----> 2 print[a] NameError: name 'a' is not defined

Important to remember is that a key has to be unique in a dictionary, no duplicates are allowed. However, in case of duplicate keys rather than giving an error, Python will take the last instance of the key to be valid and simply ignore the first key-value pair. See it for yourself:

sweet_dict = {'a1': 'cake', 'a2':'cookie', 'a1': 'icecream'} print[sweet_dict['a1']] icecream

If you want to know more about dictionaries in Python, check out this tutorial.

Python List Comprehensions vs Generator Expressions

What is List Comprehension?
It is an elegant way of defining and creating a list. List Comprehension allows us to create a list using for loop with lesser code. What normally takes 3-4 lines of code, can be compressed into just a single line.

Example:




# initializing the list

list = []

for i in range[11]:

if i % 2 == 0:

list.append[i]

# print elements

print[list]

Output:

0 2 4 6 8 10

Now, the same output can be derived from just a single line of code.




list = [i for i in range[11] if i % 2 == 0]

print[list]

Output:



0 2 4 6 8 10

What are Generator Expressions?
Generator Expressions are somewhat similar to list comprehensions, but the former doesn’t construct list object. Instead of creating a list and keeping the whole sequence in the memory, the generator generates the next element in demand.
When a normal function with a return statement is called, it terminates whenever it gets a return statement. But a function with a yield statement saves the state of the function and can be picked up from the same state, next time the function is called.
The Generator Expression allows us to create a generator without the yield keyword.

Syntax Difference: Parenthesis are used in place of square brackets.




# List Comprehension

list_comprehension = [i for i in range[11] if i % 2 == 0]

print[list_comprehension]

Output:

0 2 4 6 8 10




# Generator Expression

generator_expression = [i for i in range[11] if i % 2 == 0]

print[generator_expression]

Output:

In the above example, if we want to print the output for generator expressions, we can simply iterate it over generator object.




for i in generator_expression:

print[i, end=" "]

Output:

0 2 4 6 8 10

So what’s the difference between Generator Expressions and List Comprehensions?
The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions are memory efficient than the lists.
We can see this in the example below.




# import getsizeof from sys module

from sys import getsizeof

comp = [i for i in range[10000]]

gen = [i for i in range[10000]]

#gives size for list comprehension

x = getsizeof[comp]

print["x = ", x]

#gives size for generator expression

y = getsizeof[gen]

print["y = ", y]

Output:

x = 87624 y = 88

We just saw that generator expression are memory efficient. But, are they time efficient too? Let’s check this with an example.




#List Comprehension:

import timeit

print[timeit.timeit['''list_com = [i for i in range[100] if i % 2 == 0]''', number=1000000]]

Output:

8.118047142050102




#Generator Expression:

import timeit

print[timeit.timeit['''gen_exp = [i for i in range[100] if i % 2 == 0]''', number=1000000]]

Output:

0.7548244756850693

There is a remarkable difference in the execution time. Thus, generator expressions are faster than list comprehension and hence time efficient.




Article Tags :

Python

python-list

Practice Tags :

python-list

Read Full Article

Video liên quan

Bài mới nhất

Chủ Đề