Python Comprehensions

Python comprehensions are a way of writing concise code to generate a sequence which can be a list, tuple, dictionary, set or generator by using another sequence.

Remember it is just a way of condensing the code. it does not give any advantage in processing time.

Sometimes it may be a little difficult to debug a comprehension.

List Comprehension


Image depicts List comprehension

Dictionary Comprehension


Image contains dictionary comprehensions

Now based on this we might be tempted in tuple comprehension to enclose everything in the parenthesis. But if you try this in your python console we get a generator object not a tuple. In order to make it a tuple we need to enclose with the keyword tuple().