List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional test inside:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
The condition is like a filter that only accepts the items that evaluate to True.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
# will result in a new list of:
["banana", "cherry", "kiwi", "mango"]
The condition if x != "apple" will return True for all elements other than "apple", making the new list contain all fruits except "apple".
The condition is optional and can be omitted to simply make a copy of the list:
newlist = [x for x in fruits]
Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}
Here we have two lists named keys and value and we are iterating over them with the help of zip() function.
# Python code to demonstrate dictionary comprehension
# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
# but this line shows dict comprehension here
myDict = { k:v for (k,v) in zip(keys, values)}
print (myDict)
# output is
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
#We can use below too
# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
myDict = dict(zip(keys, values))
print (myDict)
# output is
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Here we are using the fromkeys() method that returns a dictionary with specific keys and values.
dic=dict.fromkeys(range(5), True)
print(dic)
# output is
{0: True, 1: True, 2: True, 3: True, 4: True}
Example 1:
# Python code to demonstrate dictionary creation using list comprehension
my_dict = {x: x**2 for x in [1,2,3,4,5]}
print (my_dict)
# output is
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 2:
str_dict = {x.upper(): x*3 for x in 'coding '}
print (str_dict)
# output is
{'O': 'ooo', 'N': 'nnn', 'I': 'iii', 'C': 'ccc', 'D': 'ddd', 'G': 'ggg'}
Example 1:
We can use Dictionary comprehensions with if and else statements and with other expressions too. This example below maps the numbers to their cubes that are divisible by 4.
# Python code to demonstrate dictionary comprehension using if.
new_dict = {x: x**3 for x in range(10) if x**3 % 4 == 0}
print(new_dict)
# output is
{0: 0, 8: 512, 2: 8, 4: 64, 6: 216}