Dict and List comprehensions in python are used to perform tasks with
much lesser code than you would have required to do in most of the
other programming languages.
For example i have a list and i need to perform certain operation on
all the elements of the list.
The traditional would be something lie this
squares = []
for num in range(10):
squares.append(num**2)
squares
OUTPUT :
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
With list comprehension we can do it in one line of code
The basic syntax for list comprehensions is this: [EXPRESSION FOR ELEMENT IN SEQUENCE].
code:
squares = [x**2 for x in range(10)]
OUTPUT :
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The same style can be extended to Dictionaries
A dictionary comprehension takes the form {key: value for (key, value) in iterable}
# List of tuples
openers = [(‘Shikhar’, ‘Rohit’), (‘Roy’, ‘Bairstow’), (‘Warner’, ‘Finch’)]
#To create a dictionary
openers_dict = {k: v for k, v in openers}
Answer ( 1 )
Dict and List comprehensions in python are used to perform tasks with
much lesser code than you would have required to do in most of the
other programming languages.
For example i have a list and i need to perform certain operation on
all the elements of the list.
The traditional would be something lie this
squares = []
for num in range(10):
squares.append(num**2)
squares
OUTPUT :
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
With list comprehension we can do it in one line of code
The basic syntax for list comprehensions is this: [EXPRESSION FOR ELEMENT IN SEQUENCE].
code:
squares = [x**2 for x in range(10)]
OUTPUT :
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
The same style can be extended to Dictionaries
A dictionary comprehension takes the form {key: value for (key, value) in iterable}
# List of tuples
openers = [(‘Shikhar’, ‘Rohit’), (‘Roy’, ‘Bairstow’), (‘Warner’, ‘Finch’)]
#To create a dictionary
openers_dict = {k: v for k, v in openers}
openers_dict
OUTPUT:
{‘Shikhar’:’Rohit’,’Roy’:’Bairstow’,’Warner’:’Finch’}