Dictionary and List
Question
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
It will take less than 1 minute to register for lifetime. Bonus Tip - We don't send OTP to your email id Make Sure to use your own email id for free books and giveaways
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’}