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
- As from the above info graphic, we can see that we enclose the entire comprehension within square brackets now first we write the loop and the element to be retrieved from the loop in the above case variable i, followed by a conditional statement if any.
- One use case you can see is if we want to quickly unwrap a list of list into a single list, as shown above. So traditional way is presented in the right and comprehension way is shown in the left.
Dictionary Comprehension
- Here you can see for dictionary comprehension, we enclose the entire expression in the curly brackets. Now a dictionary is characterized with key and value. So you can see the key value then we have the for loop to iterate through the dictionary “marks”.
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().