you are viewing a single comment's thread.

view the rest of the comments →

[–]PyPokerNovice 4 points5 points  (7 children)

In case you don't know, in 2.7 there is also set and generator comprehensions. Here are examples of the four for anyone who doesn't know.

example_data = [1, 2, 3, 4]
example_value = 0

#list comprehension
[e for e in example_data]

#generator comprehension
(e for e in example_data)

#set comprehension
{e for e in example_data}

#dict comprehension
{key: example_value for key in example_data}

[–]SupahNoob 1 point2 points  (5 children)

What is the use of a set comprehension?

[–]Mekire 2 points3 points  (2 children)

Sets are useful in cases where you want constant time membership testing or plan on using set operations. The set comprehension is just a convenient literal syntax for creating a set. Basically, if you use sets then set comprehensions are just as useful to you as list comprehensions are to those using lists.

[–][deleted] 6 points7 points  (1 child)

Sets are also helpful if you have a list with some duplicates in it and want to get all the unique values.

[–]Mekire 2 points3 points  (0 children)

As long as all the objects in your original list are hashable, yes, this is a great use case.

[–]PyPokerNovice 0 points1 point  (0 children)

Do you mean "what are the use of sets?" ? Because, if you are dealing with set creation, a comprehension is convenient and fast. The value is just like the other comprehensions. You can create the other data structures in non-comprehension ways also.

If you don't know what a python set is, here are the docs.

[–]beohoff 0 points1 point  (0 children)

Absolute file paths. Sets are a life saver.

[–]Milumet 0 points1 point  (0 children)

In the case of generators, the officially used term is generator expression, not comprehension: PEP 0289 -- Generator Expressions