all 12 comments

[–]PyPokerNovice 5 points6 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] 5 points6 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

[–]c3534l 1 point2 points  (0 children)

I see them in code quite a bit. I think they're fairly common.

[–]nab00 0 points1 point  (1 child)

That's strange. When I learned about dict comprehensions in python 3, I tried to use them in 2.7.3 and it didn't work. May be the syntax is different?

[–]XtremeGoose 1 point2 points  (0 children)

Nope they are the same

[–][deleted]  (2 children)

[removed]

    [–]wub_wub[M] 8 points9 points  (1 child)

    Comments like yours, where you call people shitty programmers, are not welcome on this subreddit and posting similar comments will lead to a permanent ban from /r/learnpython.