List comprehensions are an easy way to make a list out of another list.

For example:

 

list1 = [1, 2, 3, 4, 5, 6]
print(list1)

list2 = [x**2 for x in list1]
print(list2)
[1, 2, 3, 4, 5, 6][1, 4, 9, 16, 25, 36]

 

A similar construct exists for dictionaries and is called dictionary comprehension:

 

dic1 = {'Good': 4, 'Excellent': 5, 'Bad': 3}
print("Dic1 is {}".format(dic1))

dic2 = { v:k for k,v in dic1.items()}
print("Dic2 is {}".format(dic2))
Dic1 is {'Bad': 3, 'Excellent': 5, 'Good': 4}
Dic2 is {3: 'Bad', 4: 'Good', 5: 'Excellent'}
Write a comment:

*

Your email address will not be published.

© 2014 In R we trust.
Top
Follow us: