What are Dict and List comprehensions?

By Albert, 6 months ago
  • Bookmark
0

Use following list and apply list and dict comprehensions to calculate square of each element

list = [3.5,7,8,9,12]

Dict
List
Comprehensions
1 Answer
0

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].


Dictionary comprehensions

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).


Example :

list = [3.5,7,8,9,12]

squared_list = [x**2 for x in list]    # list comprehension
# output => [9, 25, 49, 64, 81, 144]

squared_dict = {x:x**2 for x in my_list}    # dict comprehension
# output => {3: 9, 5: 25, 7: 49, 8: 64, 9: 81, 12: 144}


Your Answer

Webinars

More webinars

Related Discussions

Running random forest algorithm with one variable

View More
We're Online!

Chat now for any query